Create xml with formatting

G

Guest

Hi,
I have to make a formatted (indented) xml file like this :

<?xml version="1.0"?>
<Message>
<Parent index="0" length="6">123
<Child1 index="0,1" length="6">abcd</Child1>
<Child2 index="0,2" length="6">pqrsxyz</Child2>
</Parent>
</Message>

As you can see, <Parent> node has some innertext as well as child nodes.
But, if
I make xml like this the indentation is lost. The resultant xml is like
this :

<?xml version="1.0"?>
<Message>
<Parent index="0" length="6">123<Child1 index="0,1"
length="6">99</Child1><Child2 index="0,2" length="6">pqrsxyz</Child2></Parent>
</Message>

To sum up the problem, if a node has both innertext and some child nodes,
then the entire node is written in a single line, without indentation.
How can I get the indentation in the above case??
Any help is highly appreciated.

Thanks.
 
G

Guest

Though the format looks weird, it is a valid xml.
Unfortunately, I can't change the format...
 
P

Piotr Szukalski

On Wed, 24 Aug 2005 19:26:02 -0700, cnu wrote:

Hi!
To sum up the problem, if a node has both innertext and some child nodes,
then the entire node is written in a single line, without indentation.
How can I get the indentation in the above case??

You forgot to tell how you create the XML, I _assume_ you use
System.Xml.XmlWriter. In such case try it's 'Formating' property:

xmlWriter.Formatting = System.Xml.Formatting.Indented;

Cheers,
Piotrek
 
G

Guest

I have all the xml in XmlDocument and this is how I save :

System.Xml.XmlTextWriter xtw = new XmlTextWriter(aFilePath, null);
xtw.Formatting = Formatting.Indented;
xmlDoc.Save(xtw);
xtw.Flush();
xtw.Close();
 
P

Piotr Szukalski

On Thu, 25 Aug 2005 00:41:02 -0700, cnu wrote:

Hi!
System.Xml.XmlTextWriter xtw = new XmlTextWriter(aFilePath, null);
xtw.Formatting = Formatting.Indented;
xmlDoc.Save(xtw);
xtw.Flush();
xtw.Close();

It looks like you have found a bug in .NET XmlWriter :/
The code below seems to proove it... Any MVP here?

// --- the code ---
System.Xml.XmlTextWriter xtw = new XmlTextWriter(@"c:\temp\aTest.xml", System.Text.Encoding.UTF8);
xtw.Formatting = Formatting.Indented;

xtw.WriteStartElement("Message");
xtw.WriteStartElement("Parent");
xtw.WriteAttributeString("Index", "0");
xtw.WriteAttributeString("Length", "6");
xtw.WriteString("123"); // get rid of this line and everything is ok

xtw.WriteStartElement("Child1");
xtw.WriteAttributeString("index", "0,1");
xtw.WriteAttributeString("length", "6");
xtw.WriteString("abcd");

xtw.WriteEndElement();
xtw.WriteEndElement();
xtw.WriteEndElement();

xtw.Flush();
xtw.Close();
// --- end ---

Cheers,
Piotrek
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top