如何使用XDocument获取特定的属性值

时间:2020-08-18 06:44:02

标签: linq-to-xml

我有这个xml enter image description here

这是xml:

<?xml version="1.0"?>
<model xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" identifier="id- 
5f3a493ba7067b8a30bfbf6b" 
 xmlns="http://www.opengroup.org/xsd/archimate/3.0/">
<name xml:lang="EN"></name>
<views>
<diagrams>
  <view identifier="id-4bad55d7-9619-4f21-bcc2-47ddb19d57b3">
      <name xml:lang="EN">1shape</name>
    <node xmlns:q1="" xsi:type="q1:Shape" identifier="id-97d9fcda-f478-4564-9abd-e2f544d2e292" x="10" y="30" w="1" h="1" nameinternal="BD_shapes_av_Square" shapeId="5bc59d14ec9d2633e8ea102e" angle="0" isgroup="False" alignment="" textalign="0" size="696 360">
      <label xml:lang="EN" />
      <style>
        <fillColor r="102" g="170" b="215" />
        <font name="Lato" size="13">
          <color r="255" g="255" b="255" />
        </font>
      </style>
    </node>
    <node xmlns:q2="" xsi:type="q2:Shape" identifier="id-3b754535-530f-49d2-9e7b-113df0659af9" x="226" y="114" w="1" h="1" nameinternal="BD_shapes_av_Coffee" shapeId="5dad5a884527ecc5c8c4871b" angle="0" isgroup="False" alignment="" textalign="0" size="52.3 72">
      <label xml:lang="EN" />
      <style>
        <fillColor r="102" g="45" b="145" />
        <font name="Lato" size="13">
          <color r="255" g="255" b="255" />
        </font>
      </style>
    </node>
  </view>
</diagrams>

我需要检查节点xsi:type属性值是否为Shape。 我在XDocument中加载了xml 我尝试去过节点元素

 xDocument.Descendants("views").Attributes("xsi:type");

如果我使用

xDocument.Root.Element("views"); - it returns null

谢谢!

1 个答案:

答案 0 :(得分:5)

这里有两个问题。首先,您当前正在寻找一个名为views的元素,该元素不在XML名称空间中。

您的XML不包含任何此类元素-您的根元素的这一部分:

xmlns="http://www.opengroup.org/xsd/archimate/3.0/"

...表示这是后代(包括views)的默认命名空间。

幸运的是,LINQ to XML使使用名称空间非常容易。您只需要:

XNamespace ns = "http://www.opengroup.org/xsd/archimate/3.0/";
XElement views = xDocument.Root.Element(ns + "views");

但是,它没有任何属性。看来您确实是在尝试找到 node 元素的属性。同样,您也想正确使用命名空间:

XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
var attributes = views.Descendants(ns + "node").Attributes(xsi + "type");

或遍历节点并检查值:

XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
foreach (var node in views.Descendants(ns + "node"))
{
    var type = (string) node.Attribute(xsi + "type");
    if (type is string && type.EndsWith(":Shape"))
    {
        ...
    }
}
相关问题