如何选择在C#中使用XPath节点? [英] How to select nodes with XPath in C#?
本文介绍了如何选择在C#中使用XPath节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
简单的问题,我只是想选择的&lt文本;模板>标签。下面是我的,但XPath不匹配任何东西。
公共静态无效TestXPath()
{
串XMLTEXT =&其中;?xml的版本= \1.0 \编码= \UTF-8 \独立= \是\>?;
XMLTEXT + =<属性的xmlns = \HTTP://schemas.openxmlformats.org/officeDocument/2006/extended-properties \的xmlns:VT = \http://schemas.openxmlformats.org/officeDocument/2006/ docPropsVTypes \>中;
XMLTEXT + =<模板>中性< /模板>< TotalTime> 1< / TotalTime><网页> 1< /页><词> 6< /词>中;
XMLTEXT + =< /性状>;
的XmlDocument xmlDoc中=新的XmlDocument();
xmlDoc.Load(新System.IO.StringReader(XMLTEXT));
的foreach(在xmlDoc.SelectNodes XmlNode的节点(//模板))
{
Console.WriteLine({0}:{1},node.Name,node.InnerText);
}
}
解决方案
您需要使用<一个href="http://msdn.microsoft.com/en-us/library/system.xml.xmlnamespacemanager.aspx"><$c$c>XmlNamespaceManager$c$c>因为模板元素是一个命名空间:
的XmlDocument xmlDoc中=新的XmlDocument();
xmlDoc.Load(新System.IO.StringReader(XMLTEXT));
XmlNamespaceManager的经理=新的XmlNamespaceManager(xmlDoc.NameTable);
manager.AddNamespace(NS,
http://schemas.openxmlformats.org/officeDocument/2006/extended-properties);
的foreach(在xmlDoc.SelectNodes(// ns:对模板XmlNode的节点,经理))
{
Console.WriteLine({0}:{1},node.Name,node.InnerText);
}
Simple question, I just want to select the text from the <Template> tag. Here's what I have, but the Xpath doesn't match anything.
public static void TestXPath()
{
string xmlText = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
xmlText += "<Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties\" xmlns:vt=\"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes\">";
xmlText += "<Template>Normal</Template> <TotalTime>1</TotalTime> <Pages>1</Pages> <Words>6</Words>";
xmlText += "</Properties>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(new System.IO.StringReader(xmlText));
foreach (XmlNode node in xmlDoc.SelectNodes("//Template"))
{
Console.WriteLine("{0}: {1}", node.Name, node.InnerText);
}
}
解决方案
You need to use an XmlNamespaceManager
because the Template element is in a namespace:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(new System.IO.StringReader(xmlText));
XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable);
manager.AddNamespace("ns",
"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties");
foreach (XmlNode node in xmlDoc.SelectNodes("//ns:Template", manager))
{
Console.WriteLine("{0}: {1}", node.Name, node.InnerText);
}
这篇关于如何选择在C#中使用XPath节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文