在C#中使用XPath的得到XML的所有节点值 [英] Using XPath in C# for get all the node values from XML
本文介绍了在C#中使用XPath的得到XML的所有节点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有XML:
<tcm:Component ID="tcm:481-636667" IsEditable="false" xmlns:tcm="http://www.tridion.com/ContentManager/5.0" xmlns:xlink="http://www.w3.org/1999/xlink">
<tcm:Context>
<tcm:Publication xlink:type="simple" xlink:title="07 Internal Test Publication" xlink:href="tcm:0-481-1"/>
<tcm:OrganizationalItem xlink:type="simple" xlink:title="System Resources" xlink:href="tcm:481-92640-2"/>
</tcm:Context>
<tcm:Data>
<tcm:Title>IBE - Skywards</tcm:Title>
<tcm:Type>Normal</tcm:Type>
<tcm:Schema xlink:type="simple" xlink:title="Resources" xlink:href="tcm:481-190471-8"/>
<tcm:Content>
<Resources xmlns="http://www.sdltridion.com/tridion/schemas">
<Text>
<Key>SKYRL_MBD</Key>
<Value>Miles Breakdown</Value>
</Text>
<Text>
<Key>ltSR_MB.Text</Key>
<Value>View Miles Breakdown</Value>
</Text>
<Text>
<Key>ltSR_HMB.Text</Key>
<Value>Hide Miles Breakdown</Value>
</Text>
<Text>
<Key>SKYRL_MBD_LK</Key>
<Value>Miles Breakdown</Value>
</Text>
</Resources>
</tcm:Content>
<tcm:Metadata>
<Metadata xmlns="http://www.sdltridion.com/tridion/schemas">
<Language>
<Language>English</Language>
</Language>
</Metadata>
</tcm:Metadata>
</tcm:Data>
</tcm:Component>
现在我想用C#中的方法,将以此XML作为输入,将返回所有的键和值的数据表。
Now I want to write a method in C# which will take this XML as input and will return all the "Key" and "Value" data in List.
请建议。
推荐答案
首先,声明列表保持值:
First, declare the lists to keep values:
using System.Collections.Generic;
List<string> keysList = new List<string>();
List<string> valuesList = new List<string>();
然后:
using System.Xml; // System.Xml.dll
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml); // Load(file)
var ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("tcm", "http://www.tridion.com/ContentManager/5.0");
ns.AddNamespace("xlink", "http://www.w3.org/1999/xlink");
foreach (XmlNode node in doc.SelectNodes("//*[local-name()=\"Key\"]"))
{
keysList.Add(node.InnerText);
}
foreach (XmlNode node in doc.SelectNodes("//*[local-name()=\"Value\"]"))
{
valuesList.Add(node.InnerText);
}
如果你不需要XML DOM,只XPath的评价:
if you don't need XML DOM, only XPath to evaluate:
using System.Xml.XPath; // System.Xml.dll
XPathDocument doc = null;
using (TextReader reader = new StringReader(xml))
{
doc = new XPathDocument(reader); // specify just path to file if you have such one
}
XPathNavigator nav = doc.CreateNavigator();
foreach (XPathNavigator node in (XPathNodeIterator)nav.Evaluate("//*[local-name()=\"Key\"]"))
{
keysList.Add(node.Value);
}
foreach (XPathNavigator node in (XPathNodeIterator)nav.Evaluate("//*[local-name()=\"Value\"]"))
{
valuesList.Add(node.Value);
}
这篇关于在C#中使用XPath的得到XML的所有节点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文