在XmlDocument样式中以编程方式创建XmlNode问题
问题描述:
我无法将Xml输出导入到我期望的文件中。在XmlDocument样式中以编程方式创建XmlNode问题
我想这一点:
<Book id="RED" desc="All about the color." mmtype="NO">
</Book>
但我得到的是这样的:
<Book id="RED" desc="All about the color." mmtype="NO" />
我创建的节点代码:
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);
我看不出如何设置节点以获得块结果。 也许我需要在保存之前将节点添加到节点?但我没有任何 这个特定的节点。
任何帮助,将不胜感激。
答
<Tag />
是<Tag></Tag>
的缩写形式。开放/关闭部分之间没有任何内容。
您可以通过添加一个带有空白的XmlText
作为元素的子元素来解决此问题,但从长远来看,这实际上毫无意义,因为您只是以非最佳方式直观地将其格式化。任何体面的XML解析器都应该能够读取短格式标记,因为这是推荐的行为。
+0
谢谢Aren,我明白它是一种完全可以接受的标签形式,只是想知道我是否在代码上做错了什么。它看起来只是有和没有孩子之间的区别。你的答案是现货。 – Sleff
为什么你需要它看起来像你没有孩子节点?真正好奇。 –
我想这只是为了反映过去的XML文件的使用情况。我正在编辑现有的XML文件,并希望它看起来一样。回顾现有的文件,我发现没有没有孩子的节点。所以我想我需要研究一下。 – Sleff