質問
<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>
.
私はこのXMLをONETから返却し、使用する情報を解析したいと思います。 これは、下のタグの内部テキストを試して解析するために書かれたコードです。
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のノデリストを期待しています。ただし、結果を印刷すると、結果は1のサイズです。 "ArchitectProject ArchitectProject ManagerArchitural Project Manager"
私はXmlNodeList TitleListを間違って構築しましたか?XMLツリーをさらにトラバースして処理するには、 'Title'タグの内部値を 'called'の下に入手することができますか?
解決
also_called
という名前の要素を取得します。リストにそのような要素が1つだけあります。あなたがおそらく欲しいのは、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
の代わりにXmlDocument
とLinqをXMLに使用することを検討します - それは使用が簡単です。
XDocument root = XDocument.Parse(input);
foreach (XElement titleNode in root.Descendants("also_called").First().Elements())
{
Console.WriteLine(titleNode.Value);
}
. 他のヒント
XPathのWEEビットが必要です。これにより、最初の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
とそのILKを使用する必要があることは稀であること、および/またはあなたが望むものであるかどうかを理解するためにノードを検査しようとします。XmlDocument
を使用したXMLのナビゲートはすべて、 XPath を使用することができます。特定の基準を満たすノードを取得するようになります。木や内容の内部の構造の観点から。
所属していません StackOverflow