JustCurious
JustCurious

Reputation: 820

change xml value in c#

I am working on this since yesterday. I have an XML file which looks something like this

<catalog>
  <captureInfo>
    <row>5</row>
    <col>5</col>
  </captureInfo>

  <patientInfo>
    <name>XYZ</name>
    <detail>details here</detail>
  </patientInfo>

  <imageData>
    <r0c0>
      <contrastFlag>true</contrastFlag>
    </r0c0>
    <r0c1>
      <contrastFlag>true</contrastFlag>
    </r0c1>
  </imageData>
</catalog>

I need to update the value of contrastFlag in the XML file. This is the code I have written:

XmlDocument doc = new XmlDocument();
XmlNodeList imageData = doc.GetElementsByTagName("imageData");

foreach(XmlNode node in imageData)
{
    foreach (XmlNode innernode in node)
    {
        if (innernode.Name == "r0c0")
        {
            innernode.InnerText = "false";
        }
    }
}
doc.Save("XMLFile1.xml");

Can anyone tell me where am I going wrong and also is there any better/faster approach for this?

Upvotes: 0

Views: 1570

Answers (2)

user1011627
user1011627

Reputation: 1811

Here is a way to replace all of the instances using LINQ. I just wrote out to a new file to preserve the source.

StreamReader stream = new StreamReader(@"c:\test.xml");
XDocument doc = XDocument.Load(stream);

IEnumerable<XElement> flags = doc.Descendants("contrastFlag");

foreach (XElement e in flags)
{
      e.Value = "false";
}

doc.Save(@"c:\test2.xml");

Upvotes: 1

ParanoidCoder
ParanoidCoder

Reputation: 144

Well first off, your XML is malformed, the closing should match "catalog". Why not just do this:

string xml = @"<catalog>
  <captureInfo>
    <row>5</row>
    <col>5</col>
  </captureInfo>

  <patientInfo>
    <name>XYZ</name>
    <detail>details here</detail>
  </patientInfo>

  <imageData>
    <r0c0>
      <contrastFlag>true</contrastFlag>
    </r0c0>
    <r0c1>
      <contrastFlag>true</contrastFlag>
    </r0c1>
   </imageData>
</catalog>";

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xml);
xdoc.SelectSingleNode("//catalog/imageData/r0c0/contrastFlag").InnerText = "false";

Upvotes: 3

Related Questions