Sleff
Sleff

Reputation: 99

Creating an XmlNode programatically in XmlDocument style issue

I'm having trouble getting the Xml output to file that I expect.

I want this:

<Book id="RED" desc="All about the color." mmtype="NO">

</Book>

But what I get is this:

<Book id="RED" desc="All about the color." mmtype="NO" />

My code for creating the node is:

XmlNode newNode = _xmlDocument.CreateElement("Book");
//Add Attributes
XmlAttribute attrID = _xmlDocument.CreateAttribute("id");
attrID.Value = newBook.ID;
newNode.Attributes.Append(attrID);

XmlAttribute attrDesc = this._xmlDocument.CreateAttribute("desc");
attrDesc.Value = newBook.Description;
newNode.Attributes.Append(attrDesc);

XmlAttribute attrMmType = this._xmlDocument.CreateAttribute("mmtype");
attrMmType.Value = newBook.mmType;
newNode.Attributes.Append(attrMmType);

//Add new child node to parent
parentNode.InsertBefore(newNode, parentNode.FirstChild);

I don't see how to setup the node differently to get the block outcome. Perhaps I need to add a child to the node before saving it? But I don't have any for this particular node.

Any help would be appreciated.

Upvotes: 0

Views: 1421

Answers (1)

Aren
Aren

Reputation: 55966

<Tag /> is the shortform of <Tag></Tag> Where there's nothing inbetween the open/close portions.

You may be able to get around this by adding a XmlText with whitespace as a child of the element but realize this really is pointless in the long run as you're just formatting it visually in a non-optimal way. Any decent XML Parser should be able to read short form tags as it's the recommended behaviour.

Upvotes: 2

Related Questions