Home > database >  Change Value of nested node
Change Value of nested node

Time:10-12

This seems like a simple question but I can't seem to get started on a working solution. The final goal is to change the value of the ConstantValue element highlighted below. My strategy is to find the Component node and drill down from there. The problem is that keep returning a null and I'm not sure why. Below is the code I'm using a the xml I'm using. Any hints would be great.

   XDocument xmlDoc = XDocument.Parse(str);
        var items = xmlDoc.Descendants("Component")
                            .Where(x => x.Attribute("Name").Value == "axesInterface")
                            .FirstOrDefault();

enter image description here

<?xml version="1.0" encoding="utf-8"?>
<Document>
  <Engineering version="V17" />
  <DocumentInfo> 
  </DocumentInfo>
  <SW.Blocks.FB ID="0">
    <AttributeList>     
      <Interface><Sections></Sections></Interface>
      <MemoryLayout>Optimized</MemoryLayout>
      <MemoryReserve>100</MemoryReserve>
      <Name>EM00_CM01_Warp1</Name>
      <Number>31650</Number>
      <ProgrammingLanguage>LAD</ProgrammingLanguage>
      <SetENOAutomatically>false</SetENOAutomatically>
    </AttributeList>
    <ObjectList>    
      <SW.Blocks.CompileUnit ID="4" CompositionName="CompileUnits">
        <AttributeList>
          <NetworkSource>
            <FlgNet xmlns="http://www.siemens.com/automation/Openness/SW/NetworkSource/FlgNet/v4">
                <Parts>    
                  <Access Scope="GlobalVariable" UId="27">
                    <Symbol>
                      <Component Name="HMIAxisCtrl_Interface" />
                      <Component Name="axesInterface" AccessModifier="Array">
                        <Access Scope="LiteralConstant">
                          <Constant>
                            <ConstantType>DInt</ConstantType>
                            <ConstantValue>0</ConstantValue>
                          </Constant>
                        </Access>
                      </Component>
                    </Symbol>
                  </Access>   
                </Parts>
            </FlgNet>
          </NetworkSource>         
        </AttributeList>     
      </SW.Blocks.CompileUnit>       
    </ObjectList>
  </SW.Blocks.FB>
</Document>
  

CodePudding user response:

You can use XQuery to get the correct node:

using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;

//

var nm = new XmlNamespaceManager(new NameTable());
nm.AddNamespace("sm", "http://www.siemens.com/automation/Openness/SW/NetworkSource/FlgNet/v4");

var node = xdoc.XPathSelectElement(@"//sm:Access[@Scope=""LiteralConstant""]/sm:Constant/sm:ConstantValue", nm);

node.Value = "Something Else";

enter image description here

  • Related