2016-12-17 79 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

相关问题