我正在使用以下 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>正如您所看到的,由于某种原因,我有一个重复的空“歌曲”节点,我在这里缺少什么?我在这里没有看到任何异常,有人可以帮忙吗,提前谢谢。
2 回答
杨魅力
TA贡献1811条经验 获得超6个赞
您 AppendChild 2 次element2。删除第一个
for (int i = 0; i < 5; i++)
{
XmlElement element2 = finalDoc.CreateElement(string.Empty,"song", string.Empty);
element2.SetAttribute("title", "title" + i);
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);
}
- 2 回答
- 0 关注
- 78 浏览
添加回答
举报
0/150
提交
取消