0

I am working on this since the past 2 hours.I have an XML file which looks 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>
  <imageData>
<catalog>

I want to change the value of contrastFlag. I tried this but its not working

XDocument xdoc = XDocument.Load(filename)
xdoc.Element("catalog")
                .Element("imageData")
                .Descendants()
                .Where(x => x.Value == "r0c0")
                .First()
                .SetElementValue("contrastFlag", "newValue");


            doc.Save("XMLFile1.xml");

Can I know where I am going wrong and what would be the correct approach?

4
  • 1
    Change where condition to x.Name == "r0c0" Commented May 30, 2018 at 22:41
  • i get this error - "System.NullReferenceException: Object reference not set to an instance of an object" Commented May 30, 2018 at 22:45
  • 1
    the <imageData> and <catalog> tags are not closed properly, but after that is fixed, this works for me xdoc.Element("catalog").Element("imageData").Element("r0c0").SetElementValue("contrastFlag", "newValue"); Commented May 30, 2018 at 23:04
  • From : .Where(x => x.Value == "r0c0") To: .Where(x => x.Name.LocalName == "r0c0") Commented May 31, 2018 at 0:20

2 Answers 2

1

It's not clear if you have multiple contrastFlag elements or not.

If there's only one, you can simply do this:

XDocument xdoc = XDocument.Load(filename);
var element = xdoc.Root.Descendants("contrastFlag").FirstOrDefault();
if (element != null)
    element.Value = "false";
xdoc.Save("sample1.xml");

If you have multiple elements, you can use XPath instead:

XDocument xdoc = XDocument.Load(filename);
var element = xdoc.Root.XPathSelectElement("//catalog//imageData//r0c0//contrastFlag");
if (element != null)
    element.Value = "false";
xdoc.Save("sample1.xml");

NOTE:

XPath is in using System.Xml.XPath namespace.

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

Comments

0
.Where(x => x.Name == "r0c0") 

Changed to this instead of x.Value because its an element Name.

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.