gpt4 book ai didi

c# - 遍历 XML 中的多个子节点

转载 作者:数据小太阳 更新时间:2023-10-29 01:45:22 26 4
gpt4 key购买 nike

  <Sections>
<Classes>
<Class>VI</Class>
<Class>VII</Class>
</Classes>
<Students>
<Student>abc</Student>
<Student>def</Student>
</Students>
</Sections>

我必须遍历类才能将“类”放入字符串数组中。我还必须遍历“Students”以将“Student”放入一个字符串数组中。

XDocument doc.Load("File.xml");
string str1;
foreach(XElement mainLoop in doc.Descendants("Sections"))
{
foreach(XElement classLoop in mainLoop.Descendants("Classes"))
str1 = classLoop.Element("Class").Value +",";
//Also get Student value
}

无法获得所有类(class)。此外,我需要使用 LINQ to XML 重写此而不,即使用 XmlNodeList 和 XmlNodes。

XmlDocument doc1 = new XmlDocument();
doc1.Load("File.xml");
foreach(XmlNode mainLoop in doc.SelectNodes("Sections")) ??

不确定如何去做。

最佳答案

XPath 很简单。要将结果放入数组中,您可以使用 LINQ 或常规循环。

var classNodes = doc.SelectNodes("/Sections/Classes/Class");
// LINQ approach
string[] classes = classNodes.Cast<XmlNode>()
.Select(n => n.InnerText)
.ToArray();

var studentNodes = doc.SelectNodes("/Sections/Students/Student");
// traditional approach
string[] students = new string[studentNodes.Count];
for (int i = 0; i < studentNodes.Count; i++)
{
students[i] = studentNodes[i].InnerText;
}

关于c# - 遍历 XML 中的多个子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6295961/

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