2016-12-17 49 views
0

是一排我有這個簡單的XMLC#:如何知道如果這兩個元素使用XML LINQ

<parent> 
    <child> 
     <son attribute="1"/> 
     <sp> 
     <son attribute="2"/> 
     <sp> 
    </child> 
    <child> 
     <another child> 
     <son attribute ="3"/> 
     <sp> 
     </another child> 
    </child> 
    <child> 
     <son attribute="5"/> 
    </child> 
</parent> 

這裏是我的代碼現在。其實我不知道接下來會發生什麼

XDocument doc = XDocument.Parse(string); 
foreach (var el in doc.Descendants("child").ToList()) 
{ 
} 

所以輸出將

<parent> 
     <child> 
      <son attribute="1"/> 
      <sp value="1"> 
      <son attribute="2"/> 
      <sp value="2"> 
     </child> 
     <child> 
      <another child> 
      <son attribute ="3"/> 
      <sp value="3"> 
      </another child> 
     </child> 
     <child> 
      <son attribute="5"/> 
     </child> 
    </parent> 

我的問題是,我如何檢查sonsp標籤是彼此相鄰如果相鄰,該sp標籤將得到son標籤

+0

你可能會更好嘗試使用XSLT這份工作,而不是直的C#。我有一段時間沒有使用XSLT,但C#肯定支持它,這些SO問題可能有幫助:http://stackoverflow.com/questions/23274312/how-to-match-and-wrap-identical-and-相鄰節點在一起在xslt-1-0和http://stackoverflow.com/questions/32701706/xslt-identify-consecutive-nodes-which-has-same-patters-of-attribute-values – user783836

+0

如果它不是兒子旁邊? – DarkKnight

+0

@DarkKnight沒有任何反應,例如 – imadammy

回答

1

的屬性值這是你怎麼做..

var xmldoc = XDocument.Parse(xml); 
var getReadyForSp = false; 
string sonvalue = "-1"; 

foreach (var ele1 in xmldoc.Element("parent").Elements("child")) 
foreach (var element in ele1.Elements()) 
{ 
    if (element.Name == "son") 
    { 
     getReadyForSp = true; 
     sonvalue = element.Attribute("attribute").Value; 
    } 
    if (getReadyForSp && element.Name == "sp") 
    { 
     XAttribute attribute = new XAttribute("value", sonvalue); 
     element.Add(attribute); 
     getReadyForSp = false; 
    } 

} 

但是,你需要確保SP單元具有有效的格式,這是<sp/>

+0

這個例子可以工作,但是如何處理另一個標籤內的兒子和sp標籤呢?我更新了示例先生,謝謝 – imadammy

+0

@imadammy:您是否具有預定義的元素名稱集,這些元素名稱是此嵌套結構的一部分。如果您不確定還有多少「另一種」類型的中間節點存在,邏輯會變得有點複雜。 – DarkKnight

+0

謝謝。只是增加了邏輯性陳述。 – imadammy

相關問題