Search code examples
c#xmlvisual-studiospecflow

Specflow C# - load/edit/save xml file


Im using Visual studio 2019 and I would like to load, edit and save xml file.

xml file:

<?xml version="1.0" encoding="utf-8"?>
<Firstdelivery25 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.acm.nl/Operations/2018/09">
    <Firstdelivery>
        <MessageId xmlns="http://www.acm.nl/DataModel/2018/09">
            <Source>ABC</Source>
        </MessageId>
    </Firstdelivery>
</Firstdelivery25>

Code in Visual studio:

using System.Linq;
using System.Xml.Linq;
using System.Xml;
using TechTalk.SpecFlow;
XDocument xdoc = XDocument.Load(@"C:\\XML files\\25.xml");
            var element = xdoc.Elements("Source").FirstOrDefault();
            if (element != null)
            {
                element.Value = "DEF";
            }

            xdoc.Save(@"C:\\VB_25.xml");

When I execute this, the test is passed successfully. However, when I open the new created VB_25.xml file, the old value is still there.

Any help/suggestions/tips would be appreciated.


Solution

  • You can try to modifty XML Data by using XPathNavigator.

    Here is a simple demo you can refer to.

    http://www.acm.nl/DataModel/2018/09 is the xmlns of MessageId.

    XmlDocument document = new XmlDocument();
    document.Load("test.xml");
    XPathNavigator navigator = document.CreateNavigator();
    
    XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);
    manager.AddNamespace("id", "http://www.acm.nl/DataModel/2018/09");
    
    foreach (XPathNavigator nav in navigator.Select("//id:Source", manager))
    {
        nav.SetValue("Tessssssst");
    }
    
    document.Save(@"new.xml");