简体   繁体   中英

Change xml value using linq in c#

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?

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.

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

更改为x而不是x.Value,因为它是元素名称。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM