簡體   English   中英

循環遍歷 XML 中的多個子節點

[英]Loop through multiple subnodes in XML

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

我必須遍歷 Classes 才能將“Class”放入字符串數組中。 我還必須遍歷“學生”以將“學生”放入字符串數組中。

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
        }

無法獲得所有課程。 另外,我需要在使用 LINQ 到 XML 的情況下重寫它,即使用 XmlNodeList 和 XmlNodes。

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

不知道如何 go 關於它。

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

不確定是否要為 XmlNodes 重寫它,但對於您的班級和學生,您可以簡單地:

   XDocument doc.Load("File.xml");
   foreach(XElement c in doc.Descendants("Class")) 
   {   
       // do something with c.Value; 
   }

   foreach(XElement s in doc.Descendants("Student")) 
   {   
       // do something with s.Value; 
   }

使用 LINQ 至 XML:

XDocument doc = XDocument.Load("file.xml");
var classNodes = doc.Elements("Sections").Elements("Classes").Elements("Class");
StringBuilder result = new StringBuilder();
foreach( var c in classNodes )
    result.Append(c.Value).Append(",");

使用 XPath:

XmlDocument doc = new XmlDocument();
doc.Load("file.xml");
var classNodes = doc.SelectNodes("/Sections/Classes/Class/text()");
StringBuilder result = new StringBuilder();
foreach( XmlNode c in classNodes )
    result.Append(c.Value).Append(",");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM