user2086641
user2086641

Reputation: 4371

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 Facilityand 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.

Upvotes: 1

Views: 2206

Answers (2)

StuartLC
StuartLC

Reputation: 107367

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";      

Upvotes: 2

Alejandro Techera
Alejandro Techera

Reputation: 124

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();

Upvotes: 1

Related Questions