0

Answers to similar questions aren't helping me; or I'm missing something very obvious.

I want to add a <value> element into a <question> element in XML structured like this:

<form>
    <foo>
        <bar>
            <question id="1">...</question>
            <question id="2">...</question>
        </bar>
    </foo>
</form>

Other questions seem to focus on adding an element into the root element but I'm trying to add mine further into the tree based on attribute values. I have tried the following which doesn't work:

XDocument newFormTemplateXML = XDocument.Load("newFormTemplate.xml");
XElement newValue = new XElement("value", 123);
newFormTemplateXML
    .Descendants()
    .Where(d => d.Name.ToString().Equals("question") && d.Attribute("id").Equals(1))
    .Append(newValue);
newFormTemplateXML.Save("test.xml");

I'm not getting an error message. Can someone help me on the right path please?

5
  • Try to use "Add" instead of "Append". By the way is newValue element inserted somewhere? Commented Oct 29, 2018 at 12:20
  • Also, take a look to this social.msdn.microsoft.com/Forums/vstudio/en-US/… Commented Oct 29, 2018 at 12:25
  • I've tried Add() to no avail - except for adding newValue to the root with newFormTemplateXML.Root.Add(newValue) Commented Oct 29, 2018 at 12:25
  • 2
    newFormTemplateXML.Descendants("question").Where(q => (int) q.Attribute("id") == 1).Single().Add(new XElement("boo")) works for me. Commented Oct 29, 2018 at 12:26
  • @JeroenMostert ooo that worked, thank you - do you want to post that up as an answer? Commented Oct 29, 2018 at 12:32

2 Answers 2

3

Using the "native" methods:

newFormTemplateXML
    .Descendants("question")
    .Single(q => (int) q.Attribute("id") == 1)
    .Add(newValue);

Or, for XPath lovers:

newFormTemplateXML.XPathSelectElement("//question[@id=1]").Add(newValue);

Note that this doesn't verify there is really only one question with id 1, it will modify only the first such question. The Single() call doesn't have this problem/advantage.

Sign up to request clarification or add additional context in comments.

Comments

0

Append doesn't do what you think it does. Append adds a new item to the end of a sequence and you are not wanting to add to the descendants.

XDocument newFormTemplateXML = XDocument.Load("newFormTemplate.xml");
XElement newvalue = new XElement("value", 123);
var question = newFormTemplateXML.Descendants()
    .Where(d => d.Name.ToString().Equals("question") &&   
        d.Attribute("id").Equals(1)).SingleOrDefault();
question.add(newValue)
newFormTemplateXML.Save("test.xml");

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.