1

I have a XML document in the following general format:

<Alpha>
    <Beta>
        <Gamma>
            <Delta id="1">
                ...
            </Delta>
            <Delta id="2">
                ...
            </Delta>
            ...
         </Gamma>
    </Beta>
</Alpha>

I'm looking for a way to find all of the Delta elements (regardless of how many there are) and increase the value of the id attribute by a specific value, x, and then save the document. What's the fastest way to achieve this?

0

2 Answers 2

6

The fastest in terms of the shortest amount of code?

XDocument doc = XDocument.Load("test.xml");
foreach (var id in doc.Descendants("Delta").Attributes("id"))
{
    id.SetValue((int) id + 1);
}
doc.Save("test.xml");
Sign up to request clarification or add additional context in comments.

Comments

0

Can you use LINQ to Xml (I.e what .net version are you using??). If so then this is pretty easy with Linq:

XDocument doc = XDocument.Load(source);
foreach (var deltaNode in doc.Descendants().Where(e => e.Name.LocalName == "Delta"))
    deltaNode.SetAttributeValue("id", "Whatever");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.