簡體   English   中英

XDocument麻煩閱讀XML <Document> 標簽(VB.net)

[英]XDocument troble reading XML with <Document> tag (VB.net)

我有一個看起來像這樣的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

這確實是行不通的。 我發現的是<Document>標簽將其弄亂了。 如果我刪除了這些標簽,它將理解我要這樣做。 有人知道為什么嗎?

編輯:嗯,我也剛剛發現它可以與<Document> ,在這種情況下,正是xmlns弄亂了它。 有誰知道為什么和/或如何解決這個問題? 它不會給我任何錯誤,但是會導致我在循環中得到null。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM