Search code examples
c#xmlxelement

Finding and replacing values of a tag in XML with c sharp


<TestCase Name="DEBUG">

<ActionEnvironment Name="Carved records indication">
    <Define Name="_TestedVersionPath"         Value="{CustomParam {paramName=PA tested version installer folder path}, {appName=PA installer}, {hint=\\ptnas1\builds\Temp Builds\Forensic\Physical Analyzer\PA.Test\UFED_Analyzer_17.02.05_03-00_6.0.0.128\EncryptedSetup}}"/>
    <Define Name="_PathOfdata"                Value="SharedData\myfolder\mydata.xml"/>
    <ActionSet Name="DEBUG">    
        <Actions>                                                   
            <SpecialAction ActionName="myactionname">
                <CaseName>123</CaseName>
                <UaeSendQueryValues>
                    <URL>192.168.75.133</URL>
                    <RestURL></RestURL>
                    <UserName>user1</UserName>
                    <Password>aaa</Password>
                    <PathOfQuery>_PathOfdata</PathOfQuery>
                    <Method>GET</Method>
                    <ParamsFromFile></ParamsFromFile>
                </UaeSendQueryValues>                                       
            </SpecialAction>
        </Actions>          
    </ActionSet>    
</ActionEnvironment>    

I have the above xml. i need to find every PathOfQuery tag, get the text of it (in the example _PathOfdata) and then go up in the xml tree and find the first Define tag who's name = to text of PathofQuery tag and get its value (in the example "SharedData\myfolder\mydata.xml")

then i would like to replace that value with another string.

i need to do this for each PathofQuery tag that appears in the xml (it could be more then one) and i want to find always the first apparition of the Define tag (could be more than one) when i travel the tree up from the point where the PathofQuery tag was found.

I want to do this on C Sharp

any help will be appreciated.


Solution

  • Let's assume string s holds the above Xml. Then the following code will work for you:

        XmlDocument xDoc = new XmlDocument();
        xDoc.LoadXml(s);
    
        XmlNode pathOfQuery = xDoc.SelectSingleNode("//PathOfQuery");
        string pathOfQueryValue = pathOfQuery.InnerText;
        Console.WriteLine(pathOfQueryValue);
        XmlNode define = xDoc.SelectSingleNode("//Define[@Name='" + pathOfQueryValue + "']");
        if(define!=null)
        {
            string defineTagValue = define.Attributes["Value"].Value;
            Console.WriteLine(defineTagValue);
    
            pathOfQuery.InnerText = defineTagValue;
    
            Console.WriteLine(pathOfQuery.InnerText);
        }