Search code examples
c#xmlautodesk-navisworks

Set the value of a node in xml file to be equal to another value of node in C#


Assuming that I have following XML:

<?xml version="1.0" encoding="UTF-8" ?>

<exchange xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://download.autodesk.com/us/navisworks/schemas/nw-exchange-12.0.xsd" units="ft" filename="" filepath="">
  <batchtest name="3636" internal_name="3636" units="ft">
    <clashtests>
      <clashtest name="Ducts VS Ducts" test_type="hard" status="new" tolerance="0.0000000000" merge_composites="0">
        <linkage mode="none"/>
        <left>
          <clashselection selfintersect="0" primtypes="1">
            <locator>/</locator>
          </clashselection>
        </left>
        <right>
          <clashselection selfintersect="0" primtypes="1">
            <locator>/</locator>
          </clashselection>
        </right>
        <rules/>
      </clashtest>
      <clashtest name="Ducts VS Cable Trays" test_type="hard" status="new" tolerance="0.0000000000" merge_composites="0">
        <linkage mode="none"/>
        <left>
          <clashselection selfintersect="0" primtypes="1">
            <locator>/</locator>
          </clashselection>
        </left>
        <right>
          <clashselection selfintersect="0" primtypes="1">
            <locator>/</locator>
          </clashselection>
        </right>
        <rules/>
      </clashtest>
      
      </batchtest>
</exchange>

I want to do like this image using C# in Visual Studio

enter image description here

I want to change the value of locator node to depend on the value of clash test node as shown in the image.


Solution

  • Use xml linq :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    using System.Text.RegularExpressions;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
    
                foreach (XElement clashtest in doc.Descendants("clashtest"))
                {
                    string name = (string)clashtest.Attribute("name");
                    string pattern = "(?'name1'.*)VS(?'name2'.*)";
                    Match match = Regex.Match(name, pattern);
                    string name1 = match.Groups["name1"].Value.Trim();
                    string name2 = match.Groups["name2"].Value.Trim();
    
                    List<XElement> locators = clashtest.Descendants("locator").ToList();
                    locators[0].SetValue(name1);
                    locators[1].SetValue(name2);
                }
            }
        }
    }