使用XML命名空间前缀C#搜索XML元素 [英] Search XML element with xml namespace prefix C#
问题描述
更新
我想有一个表达式(XPath的,或正则表达式表达类似的),可以与特定匹配的XML元素命名空间。例如,我想找到的链接元素的值(如我所需要的的http:// URL中< B:链接>的http:// URL< / B:链接>)
如下图所示。然而,命名空间前缀根据不同的XML文件,如图1-3的情况下变化。
I want to have an expression (XPath, or Regex Expression, similar) that can match an XML element with a particular namespace. For example, I want to locate the value of the link element (e.g. I need the http://url within <b:link>http://url</b:link>)
shown below. However, the namespace prefix varies depending on different xml files as shown in cases 1-3.
考虑空间前缀允许的字符(如被任何字符允许/有效) ,任何人都可以提供解决方案(XPath中,正则表达式或类似用语?
Considering the allowed character for namespace prefix (e.g. is any character allowed/valid) , could anyone provide the solution (XPath, Regex Expression or similar?
请注意,由于XML文件是未知的,因此命名空间和前缀是未知的,直到运行时。这是否意味着我不能用这个的XDocument / XmlDocument的,因为它需要命名空间中的代码是已知的。
Please note that because the xml file is unknown, thus, the namespace and prefix are unknown until runtime. Does it mean I cannot use this XDocument/XmlDocument, because it requires namespace to be known in the code.
更新
案例1
<A xmlns:b="link">
<b:link>http://url
</b:link>
</A>
案例2
<A xmlns="link">
<link>http://url
</link>
</A>
案例3
<A xmlns:a123="link">
<a123:link>http://url
</a123:link>
</A>
请注意,链接元素中的URL可以是任何HTTP URL,以及未知的,直到运行时。
Please note that the url within the link element could be any http url, and unknown until runtime.
更新
请标记我的问题。
推荐答案
您需要知道你将处理的命名空间,并与XmlNamespaceManager的注册。下面是一个例子:
You need to know the namespaces you will be dealing with and register them with an XmlNamespaceManager. Here is an example:
XmlDocument doc = new XmlDocument();
doc.LoadXml("<A xmlns:b='link'><b:Books /></A>");
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("b", "link");
XmlNodeList books = doc.SelectNodes("//b:Books", nsmgr);
如果你想做到这一点使用的XDocument,我会建议其简洁,这里是如何
And if you want to do this using XDocument, which I would recommend for its brevity, here is how:
XDocument xDoc = XDocument.Parse("<A xmlns:b='link'><b:Books /></A>");
XNamespace ns = "link";
var books = xDoc.Descendants(ns + "Books");
如果你不知道该命名空间(S)提前,的see这个帖子它展示了如何使用跨仅本地名称一个XDocument查询。这里有一个例子:
If you do not know the namespace(s) ahead of time, see this post which shows how to query across an XDocument using only the local name. Here's an example:
XDocument xDoc = XDocument.Parse("<A xmlns:b='link'><b:Books /></A>");
var books = xDoc.Descendants().Where(e => e.Name.LocalName.ToLower() == "books");
这篇关于使用XML命名空间前缀C#搜索XML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!