简体   繁体   中英

c#: how to know if the two element are in a row using xml linq

i have this simple xml

<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>

here is my code for now. actually i dont know what's next

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

so the output will be

<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>

my problem is how do i check if the son and sp tag are next to each other, if its next to each other, the sp tag will get the attribute value of the son tag

This is how you do it..

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;
    }

}

But you need to make sure sp element has valid format, which is <sp/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM