[英]Select all the nodes which have namespace in XML using C#
Hi can anybody help me out. 嗨,有人可以帮我吗。 I have a XML which contains my own namespace xmlns:NS .
我有一个XML,其中包含我自己的名称空间xmlns:NS。 I need to select all the nodes which contains the namespace "NS".
我需要选择包含名称空间“ NS”的所有节点。 How can we do this using C#.net.
我们如何使用C#.net做到这一点。
I tried like below: 我尝试如下:
XmlDocument doc=new XmlDocument();
doc.Load(Path);
XmlNodeList oNodeList=doc.GetElementByTagname("NS:Text");
Here i am getting all the nodes which have "NS:Text" namespace. 在这里,我得到所有具有“ NS:Text”名称空间的节点。 But I need to select all the nodes like below:
但是我需要选择所有的节点,如下所示:
XmlDocument doc=new XmlDocument();
doc.Load(Path);
XmlNodeList oNodeList=doc.GetElementByTagname("NS");
so that i can select all the nodes which contains namespace "NS". 这样我就可以选择包含名称空间“ NS”的所有节点。 but this is not working.
但这不起作用。 How can we achieve this?
我们怎样才能做到这一点?
Following is my XML format. 以下是我的XML格式。
<xml 1.0 ?>
<Root xmlns:NS="www.yembi.com">
<NS:Entry Value="User">
<table>
<tr>
<td>
<NS:display type="Label" name="First Name">
</td>
</tr>
<tr>
<td>
<NS:Text type="Text">
</td>
</tr>
<tr>
<td>
<NS:Button Type="SubmitButton" name="submit">
</td>
</tr>
</table>
</NS:Entry>
I'd like to suggest LINQ to XML if you've .net framework version 3.5 or higher. 如果您的.net Framework版本为3.5或更高版本,我想建议使用LINQ to XML。
XDocument doc = XDocument.Load(Path);
XNamespace ns = "www.yembi.com";
var result = doc.Root.Descendants()
.Where(p => p.GetPrefixOfNamespace(ns) == "NS");
You can use an XPath expression with the SelectNodes
method . 您可以将XPath表达式与
SelectNodes
方法一起使用 。
XmlDocument doc = new XmlDocument();
doc.Load(Path);
XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
mgr.AddNamespace("NS", "www.yembi.com");
XmlNodeList oNodeList = doc.SelectNodes("//NS:*", mgr);
The XPath expression //NS:*
selects any element with the NS
prefix. XPath表达式
//NS:*
选择带有NS
前缀的任何元素。
One note on your question: NS
is not a namespace in your Xml document, it is just a namespace prefix. 关于您的问题的一个注释:
NS
不是Xml文档中的名称空间,它只是名称空间前缀。 www.yembi.com
is your namespace. www.yembi.com
是您的名称空间。
You can think of the prefix as a local (within the document) placeholder for the namespace that connects the namespace with the identifiers in the document. 您可以将前缀视为该名称空间的本地(在文档中)占位符,该名称空间将名称空间与文档中的标识符连接起来。 You can easily change the placeholder in the XPath-related code (eg to
x
), and leave the NS
in the document, and things will still work, as long as it's still the namespace www.yembi.com
. 您可以轻松地在与XPath相关的代码中更改占位符(例如,更改为
x
),并将NS
保留在文档中,只要它仍然是名称空间www.yembi.com
,一切就仍然可以www.yembi.com
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.