【问题标题】:XDocument troble reading XML with <Document> tag (VB.net)XDocument 使用 <Document> 标签读取 XML 时遇到问题 (VB.net)
【发布时间】:2013-06-07 07:01:11
【问题描述】:

我有一个如下所示的 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:iso:std:iso:20022:tech:xsd:pain.008.001.02"> 
  <AllThingsInThisDocument> 
    <Headerstuff>
       <Date>2013-06-11</Date>
    </Headerstuff>
    <Reports>
      <Report>
        <Id>01</Id>
        <Name>AA</Name>
      </Report>
      <Report>
        <Id>02</Id>
        <Name>BB</Name>
      </Report>
      <Report>
        <Id>03</Id>
        <Name>CC</Name>
      </Report>
    </Reports>
  </AllThingsInThisDocument> 
</Document> 

我想要做的是循环所有的报告,我使用这个代码:

Dim xmlr As XDocument = XDocument.Load("MyMxlFile.xml")
For Each report As XElement In xmlr.Descendants("Report")
   'Do some cool stuff
Next

这确实不起作用。我发现是 &lt;Document&gt; 标签搞砸了。如果我删除这些标签,它就知道我想要这样做。 有人知道为什么吗?

编辑:好吧,我也刚刚发现它确实可以与&lt;Document&gt; 一起使用,在这种情况下是 xmlns 搞砸了。任何人都知道为什么和/或如何解决这个问题? 它没有给我任何错误,但它给了我 null 作为循环的结果。

【问题讨论】:

    标签: xml vb.net xml-parsing linq-to-xml


    【解决方案1】:

    您的 XML 文档使用命名空间,因此您必须在 LINQ to XML 查询中使用它。

    首先,使用共享XNamespace.Get()方法创建XNamespace实例:

    Dim ns = XNamespace.Get("urn:iso:std:iso:20022:tech:xsd:pain.008.001.02")
    

    然后使用XNamespace + string 运算符在查询中使用它:

    For Each report As XElement In xmlr.Descendants(ns + "Report")
       ' Do some cool stuff '
    Next
    

    【讨论】:

      猜你喜欢
      • 2015-10-19
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 1970-01-01
      • 2015-08-04
      • 1970-01-01
      相关资源
      最近更新 更多