1

I am wondering how do you go about updating an XML string using XML document...

I will be changing the values of attributes in an xmlDocument (this will be a large string)... Looking online I was a little confused about the proper way to do this... Here is a sample of what I am trying to do...

    //get the value at the key from the form collection
    var value = formCollection[key.ToString()];
    //lookup the specifc <node> in the xml file and match it to the key... should be equal to the path's array found in _EditTemplate values above...
    XmlNode xElm = xmlTemplate.SelectSingleNode(string.Format("//dataTemplateSpecification/templates/template/elements/element[@name=\"{0}\"]", key.ToString()));
                //get the value attribute va                    
    XmlAttribute tempAtt = xElm.Attributes["value"];// = formCollection[key.ToString()];
                //Attempt to set the attribute value to the correct value
    tempAtt.Value = value;// formCollection[key.ToString()];

Does that seem like a rational way to update an xml String? Remember, I don't want to save this to a file. I want to update the string and go from there I need to do more processing...

1
  • Just looked at a quick tutorial... Would doing this work... xmlTemplate.SelectSingleNode(string.Format("//dataTemplateSpecification/templates/template/elements/element[@name=\"{0}\"]", key.ToString())).Attributes["value"].Value = value; xmlTemplate.Save(Tmplts); Only one way to find out... Commented Jul 13, 2011 at 13:26

1 Answer 1

3

If I just wanted to set an attribute value (without looking at the previous value), I'd use XmlElement.SetAttribute.

(As an aside, if you're using .NET 3.5 or higher, I would definitely look at LINQ to XML instead of the original DOM API.)

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

9 Comments

Why is Linq to XMl preferred over DOM?
@saj: It's simply a much nicer API to work with, both for producing XML and querying it.
@saj, it's much easier to use and integrates seamlessly with the rest of your objects. And when you're done the code is much easier to read.
How would I navigate to the appropriate XmlAttribute though? I know about LINQ to xml and I agree it would be simpler to use. However, it's a long story why I am not using it.
@DmainEvent: You'd navigate to the appropriate element rather than the attribute. It looks like you're already doing that.
|

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.