gpt4 book ai didi

C# XML 获取重复的空节点?

转载 作者:行者123 更新时间:2023-11-30 22:53:10 24 4
gpt4 key购买 nike

我正在使用以下 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>

如您所见,由于某种原因我有一个重复的空“歌曲”节点,我在这里缺少什么?

我没有发现这里有任何问题,请有人帮忙,在此先感谢。

最佳答案

您 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);
}

关于C# XML 获取重复的空节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57553955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com