简体   繁体   English

从属性值解析XML名称空间

[英]Resolving xml namespace from attributes values

Given the following xml (simplified) 给定以下xml(简体)

<root xmlns="http://schemas.datacontract.org/2004/07/Base" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <Items>
        <item xmlns:a="http://schemas.datacontract.org/2004/07/Base" i:type="a:A"></item>
        <item xmlns:a="http://schemas.datacontract.org/2004/07/Base" i:type="a:B"></item>
    </Items>
</root>

I'm trying to do something along these line. 我正在尝试沿着这些路线做点事情。

XNamespace xmlInstanceNs = "http://www.w3.org/2001/XMLSchema-instance";
XNamespace baseNs = "http://schemas.datacontract.org/2004/07/Base";
var items = root.Descendants(baseNs + "item");
var aItems = items.Where(i => i.Attribute(xmlInstanceNs + "type").Value == baseNs + "A");

Of course this isnt working since the last line is basically comparing the string "a:A" to the XName "{ http://schemas.datacontract.org/2004/07/Base }A" which arent identical. 当然,这是行不通的,因为最后一行基本上将字符串“ a:A”与XName“ { http://schemas.datacontract.org/2004/07/Base } A”进行比较,后者没有相同之处。

Is there a way to parse the "a:A" string to its XName equivalent without having to manually iterate the xml to find all the namespace abbreviations? 有没有一种方法可以将“ a:A”字符串解析为其等效的XName,而无需手动迭代xml来查找所有名称空间的缩写?

There is http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.getnamespaceofprefix%28v=vs.110%29.aspx so you should be able to compare http://msdn.microsoft.com/zh-cn/library/system.xml.linq.xelement.getnamespaceofprefix%28v=vs.110%29.aspx,因此您应该能够进行比较

items.Where(i => 
  baseNs  + "A" == 
  i.GetNamespaceOfPrefix(i.Attribute(xmlInstanceNs + "type").Value.Split(new Char[] { ':' })[0]) + "A")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM