【问题标题】:How to get specific attribute value with XDocument如何使用 XDocument 获取特定属性值
【发布时间】:2020-08-18 06:44:02
【问题描述】:

我有这个 xml

这是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

提前致谢!

【问题讨论】:

  • 请以 text 形式而不是图像形式发布一个 XML 的最小示例。我的猜测是这是一个命名空间问题,但我们无法判断,因为 XML 被裁剪了。
  • 这既不是一个最小的例子也不是完整的 - 虽然它 足以让我回答这个问题(我现在正在做),如果在未来的问题中它会非常方便您提供了minimal reproducible example。见codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question

标签: linq-to-xml


【解决方案1】:

这里有几个问题。首先,您当前正在寻找一个名为 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"))
    {
        ...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多