Xdocument - 使用Prefix读取属性的值

San*_*ile 3 c# linq linq-to-xml

很容易找到Xdocument属性的值,但我们如何找到带有prefix/Namespace的属性.

XML代码

 <label:label xlink:type="resource" xlink:label="something" xlink:lang="en" xlink:id="res_4">My value</label:label>
Run Code Online (Sandbox Code Playgroud)

我试图读取属性值xlink:Id(其中p是XElement)

p => p.Attribute("xlink:id").Value 
Run Code Online (Sandbox Code Playgroud)

这根本不起作用.

har*_*r07 5

鉴于您在XML中的某处声明了名称空间前缀:

xmlns:xlink="dummy.url"
Run Code Online (Sandbox Code Playgroud)

您可以使用XNamespace指向上面的名称空间URI的变量来访问名称空间中的属性:

XNamespace xlink = "dummy.url";
.....
p => p.Attribute(xlink+"id").Value
//or simply cast the XAttribute to string 
//to avoid exception when the attribute not found in p
p => (string)p.Attribute(xlink+"id")
Run Code Online (Sandbox Code Playgroud)