简体   繁体   中英

Select an XML node with a given child value and update a different child element

I have the following xml file:

<LabelImageCreator xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <PrintFieldList>
    <PrintFieldDefinition>
      <FieldName>Facility</FieldName>
      <DataParameterName>Address</DataParameterName>
      <FieldFont>
        <FontName>Arial</FontName>
        <FontSize>10</FontSize>
        <FontStyle>Regular</FontStyle>
      </FieldFont>
      <CurrentDataValue/>
    </PrintFieldDefinition>
    <PrintFieldDefinition>
      <FieldName>Country</FieldName>
      <DataParameterName>CountryofOrigin</DataParameterName>
      <WrapField>false</WrapField>
      <FieldFont>
        <FontName>Arial</FontName>
        <FontSize>8</FontSize>
        <FontStyle>Regular</FontStyle>
      </FieldFont>
      <CurrentDataValue/>
      <TextPrefix>Produce of </TextPrefix>
    </PrintFieldDefinition>
  <PrintFieldList>
<LabelImageCreator>

I have to select the attribute with field name Facility and add the address(eg: No 2546, Gorrge street, California, US) to <CurrentDataValue/> field and save it.

I tried with the below code,

 XmlDocument xmlDocument = new XmlDocument();
  xmlDocument.Load(path);
  var node = xmlDocument.DocumentElement.SelectSingleNode(
             "./PrintFieldList/PrintFieldDefinition[@FieldName='Facility']");

Above code while debuging it is not working. Can any one guide me how to select and update the xml attribute.

A couple of minor issues:

  • You need to start from the root element LabelImageCreator
  • FieldName is an element, not an attribute, so hence FieldName and not @FieldName
  • The closing tags on the Xml Document don't match up.

If you want to select the child element CurrentDataValue of parent PrintFieldDefinition with the child FieldName with value Facility :

var node = xmlDocument.DocumentElement.SelectSingleNode(
"/LabelImageCreator/PrintFieldList/PrintFieldDefinition[FieldName='Facility']/CurrentDataValue");

Changing the value is then simply:

node.InnerText = "No 2546, Gorrge street, California, US";      

I would use XDocument instead of XmlDocument (it allows you to use linq which in my opinion, is easier than using xpath).

You can find your node like this and I believe you can update them too (first search and get the value, then search again and update on the other node).

Example:

var nodesMatching = from node in myXDocument.Descendants()
where node.Name.LocalName.Equals("mySearchNode")
select node;
var node = nodesMatching.FirstOrDefault();

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