[英]Inner XML tag Parsing Using C#
<career code="17-1011.00">
<code>17-1011.00</code>
<title>Architects</title>
<tags bright_outlook="false" green="true" apprenticeship="false" />
<also_called>
<title>Architect</title>
<title>Project Architect</title>
<title>Project Manager</title>
<title>Architectural Project Manager</title>
</also_called>
<what_they_do>Plan and design structures, such as private residences, office buildings, theaters, factories, and other structural property.</what_they_do>
<on_the_job>
<task>Consult with clients to determine functional or spatial requirements of structures.</task>
<task>Prepare scale drawings.</task>
<task>Plan layout of project.</task>
</on_the_job>
</career>
我已經采用了從ONet返回的XML,並想解析該信息以供使用。 這是我編寫的用於嘗試解析標記下的內部文本的代碼,其中“輸入”是Onet XML。
XmlDocument inputXML = new XmlDocument();
inputXML.LoadXml(input);
XmlElement root = inputXML.DocumentElement;
XmlNodeList titleList = root.GetElementsByTagName("also_called");
for (int i = 0; i < titleList.Count; i++)
{
Console.WriteLine(titleList[i].InnerText);
}
我期待一個大小為4的NodeList。 但是,當我打印出結果時,結果的大小為1:“ ArchitectProject Architect ArchitectProject ManagerArchitectural Project Manager”
我是否將XMLNodeList titleList構造錯誤? 如何進一步遍歷和處理XML樹,以獲取“ also_drawn”下“ title”標簽的內部值?
您將獲得名為also_called
的元素。 您的列表中只有一個這樣的元素。 您可能想要的是獲取also_called
節點的子級。
例如:
XmlNodeList also_calledList = root.GetElementsByTagName("also_called");
XmlNode also_calledElement = also_calledList[0];
XmlNodeList titleList = also_calledElement.ChildNodes;
foreach (XmlNode titleNode in titleList)
{
Console.WriteLine(titleNode.InnerText);
}
另外,考慮使用XDocument
和LINQ to XML而不是XmlDocument
使用起來簡單得多:
XDocument root = XDocument.Parse(input);
foreach (XElement titleNode in root.Descendants("also_called").First().Elements())
{
Console.WriteLine(titleNode.Value);
}
您只需要一點點XPath。 這樣會選擇所有title
節點,它們是第一個also_called
子節點。
XmlDocument inputXML = new XmlDocument();
inputXML.LoadXml(input);
foreach(var node in root.SelectNodes("also_called[1]/title"))
{
Console.WriteLine(node.InnerText);
}
很少需要使用GetElementsByTagName
或ChildNodes
及其ChildNodes
和/或嘗試檢查一個節點以弄清楚它是否是您想要的那個節點。 使用XmlDocument
導航Xml就是要使用XPath ,在獲取滿足特定條件的節點時,可以使用XPath進行大量指定。 無論是在樹內的結構還是在內容上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.