簡體   English   中英

使用“動態”節點解析xml文檔

[英]Parse an xml document with “dynamic” nodes

我正在通過XDocument解析XML,我怎樣才能檢索所有語言,即<en><de><CodeCountry>及其子元素?

<en>
  <descriptif>In the historic area, this 16th century Town House on 10,764 sq. ft. features 10 rooms and 3 shower-rooms. Period features include a spiral staircase. 2-room annex house with a vaulted cellar. Period orangery. Ref.: 2913.</descriptif>
  <prox>NOGENT-LE-ROTROU.</prox>
  <libelle>NOGENT-LE-ROTROU.</libelle>
</en>
<de>
  <descriptif>`enter code here`In the historic area, this 16th century Town House on 10,764 sq. ft. features 10 rooms and 3 shower-rooms. Period features include a spiral staircase. 2-room annex house with a vaulted cellar. Period orangery. Ref.: 2913.</descriptif>
  <prox>NOGENT-LE-ROTROU.</prox>
</de>
...
<lang>
  <descriptif></descriptif>
  <prox></prox>
  <libelle></libelle>
</lang>

由於您的xml文檔格式不正確,您應該首先添加根元素。 你可能會做那樣的事情。

var content = File.ReadAllText(@"<path to your xml>");
var test = XDocument.Parse("<Language>" + content + "</Language>");

然后,當你有“動態頂級節點”時,你可以嘗試與他們的孩子(似乎不是動態的)一起工作,假設所有節點至少有一個“descriptif”孩子。 (如果它不是“descriptif”,它可能是“prox”或“libelle”)**。

//this will give you all parents, <en>, <de> etc. nodes
var parents = test.Descendants("descriptif").Select(m => m.Parent);

然后你可以選擇語言和兒童。 我使用匿名類型,你當然可以投射到自定義類。

var allNodes = parents.Select(m => new
            {
                name = m.Name.LocalName,
                Descriptif = m.Element("descriptif") == null ? string.Empty : m.Element("descriptif").Value,
                Prox = m.Element("prox") == null ? string.Empty : m.Element("prox").Value ,
                Label = m.Element("libelle") == null ? string.Empty : m.Element("libelle").Value
            });

這當然不是大文件的高性能代碼,但是......這是另一個問題。


**最壞的情況,你可能會這樣做

var parents = test.Descendants("descriptif").Select(m => m.Parent)
                .Union(test.Descendants("prox").Select(m => m.Parent))
                .Union(test.Descendants("libelle").Select(m => m.Parent));

暫無
暫無

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

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