【问题标题】:Problem getting XML elements in an SVG file在 SVG 文件中获取 XML 元素的问题
【发布时间】:2010-11-23 18:49:34
【问题描述】:

我正在尝试读取具有以下内容的非常基本的 SVG 文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="600" height="300" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <g stroke="black" >
        <line x1="75" y1="160" x2="525" y2="160" stroke-width="10"/>
    </g>
</svg>

我正在尝试获取线条元素的集合。但是,下面的代码不起作用:

XDocument XD = XDocument.Load(PathToFile);
XElement SVG_Element = XD.Root;
var adam = SVG_Element.Elements("line");

检查变量后,文档已正确加载,但变量“adam”仍为空,就好像它没有找到任何具有该名称的元素一样。任何帮助表示赞赏。

编辑:使用后代并不能解决此问题。它仍然是空的。

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:

    好吧,伙计们,我确实想通了。显然我需要将命名空间指定为 QName 的一部分:

    var adam = SVG_Element.Descendants("{http://www.w3.org/2000/svg}line");
    

    【讨论】:

    • 有类似的问题。通过使用 xdoc.Root.GetDefaultNamespace(); 然后 xdoc.Root.Element($"{{{ns}}}defs"); ...
    • 这解决了我的问题。非常感谢@Adam S
    【解决方案2】:

    line 元素是根的孙子,而不是子元素。请改用 XDocument 的 Descendants() 方法。

    【讨论】:

    • 感谢您的提示。不幸的是,即使使用后代也不能给我任何东西。
    【解决方案3】:

    试试这样的:

    Dim xmldoc As XDocument = XDocument.Load(Server.MapPath("PathtosvgFile"))
    
            Dim Info As IEnumerable(Of XElement) = _
                From typeElement In xmldoc.Descendants.Descendants
                Where typeElement.Parent = "g"
                Select typeElement
    
            Dim tel As XElement
    
            For Each tel In Info.DescendantsAndSelf.Distinct()
             'Access each descendant here and do something.
            Next
    

    【讨论】:

      【解决方案4】:

      我从未使用 XDocument 来解析 Xml 文件。我使用 XmlDocument。但我相信两者都以类似的方式工作。 我的猜测是您应该首先查询“g”元素,然后查询“line”元素,如下所示:

      XDocument XD = XDocument.Load(PathToFile);
      XElement SVG_Element = XD.Root;
      var gs = SVG_Element.Elements("g");
      var adam = gs[0].Elements("line");

      希望对你有帮助。

      【讨论】:

      • 它也找不到“g”元素。
      【解决方案5】:
      XDocument SVGDoc = XDocument.Load(yourfile);
      XElement svg_Element = SVGDoc.Root;
      
      IEnumerable<XElement> gElement = from e1 in svg_Element.Elements("{http://www.w3.org/2000/svg}g")
                                       select e1;
      int nCounter = 0;
      foreach (XElement myElement in gElement)
      {
          ... 
      }
      

      【讨论】:

      • 按原样,您的回答没有帮助。请考虑解释为什么这可能是正确的解决方案。
      • 另外,6 年前,这已经得到了基本相同的答案,但更短且没有多余的代码。
      猜你喜欢
      • 1970-01-01
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多