我正在使用以下 C# 代码创建 xml 文档:
XmlDocument finalDoc = new XmlDocument();
//(1) the xml declaration is recommended, but not mandatory
XmlDeclaration xmlDeclaration = finalDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = finalDoc.DocumentElement;
finalDoc.InsertBefore(xmlDeclaration, root);
//(2) string.Empty makes cleaner code
XmlElement element1 = finalDoc.CreateElement(string.Empty, "root", string.Empty);
finalDoc.AppendChild(element1);
for (int i = 0; i < 5; i++)
{
XmlElement element2 = finalDoc.CreateElement(string.Empty,"song", string.Empty);
element2.SetAttribute("title", "title" + i);
element1.AppendChild(element2);
for (int k=0; k<5;k++)
{
XmlElement element3 = finalDoc.CreateElement(string.Empty, "line", string.Empty);
element3.InnerText = "text " + k;
element2.AppendChild(element3);
}
element1.AppendChild(element2);
}
finalDoc.Save("C:\\Users\\adm\\Downloads\\finalDoc.xml");
我得到以下输出:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<song title="title 0" />
<song title="title 0">
<line>text 0</line>
<line>text 1</line>
<line>text 2</line>
<line>text 3</line>
<line>text 4</line>
</song>
<song title="title 1" />
<song title="title 1">
...
</song>
...
</root>
正如您所看到的,由于某种原因,我有一个重复的空“歌曲”节点,我在这里缺少什么?
我在这里没有看到任何异常,有人可以帮忙吗,提前谢谢。
杨魅力
尚方宝剑之说
相关分类