Jey
Jey

Reputation: 2127

How to update the XMLDocument using c#?

I want to update the xml document and i need to return the updated xml in string. I am trying like below. when i save the document it expects the file name. but i dont want to save this as file. i just want to get the updated xml in string.

        string OldXml = @"<Root>
                                  <Childs>
                                    <first>this is first</first>
                                    <second>this is second </second>
                                  </Childs        
                                  </Root>";

        XmlDocument NewXml = new XmlDocument();
        NewXml.LoadXml(OldXml );

        XmlNode root = NewXml.DocumentElement;
        XmlNodeList allnodes = root.SelectNodes("*");

        foreach (XmlNode eachnode in allnodes)
        {
            if (eachnode.Name == "first")
            {
                eachnode.InnerText = "1";
            }
        }

        NewXml.Save();
        string newxml = NewXml.OuterXml;

Upvotes: 0

Views: 101

Answers (2)

Alex
Alex

Reputation: 8116

Your iteration never reaches a node called "first". Else it would work fine without saving the NewXml.

You could however use a XElement and iterate over all descendants.

   string OldXml = @"<Root>
                      <Childs>
                      <first>this is first</first>
                      <second>this is second </second>
                      </Childs>        
                      </Root>";

            var NewXml = XElement.Parse(OldXml);
            foreach (var node in NewXml.Descendants())
            {
                if (node.Name.LocalName == "first")
                {
                    node.Value = "1";
                }
            }
            var reader = NewXml.CreateReader();
            reader.MoveToContent();
            string newxml = reader.ReadInnerXml();

Upvotes: 0

cuongle
cuongle

Reputation: 75306

You don't need to call Save method because string is immutable, your problem is in root.SelectNodes("*"), it just get child nodes, not all level of nodes. You need to go one more level:

  foreach (XmlNode eachnode in allnodes)
        {
            var firstNode = eachnode.ChildNodes.Cast<XmlNode>()
                              .SingleOrDefault(node => node.Name == "first");
            if (firstNode != null)
            {
                firstNode.InnerText = "1";
            }
        }


  string newxml = NewXml.OuterXml;

It would be strongly recommended using LINQ to XML, it's simpler:

var xDoc = XDocument.Parse(OldXml);
foreach (var element in xDoc.Descendants("first"))
    element.SetValue(1);

string newXml = xDoc.ToString();

Upvotes: 1

Related Questions