简体   繁体   中英

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.

var element = xdoc.Elements("Source").FirstOrDefault();

Given your provided XML elements will always be null and so you do nothing with your XML and that's why the result looks like the input.

Reason1: Elements() is looking for direct children only and <Source> is not a direct child in your doc.

See https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xcontainer.elements?view=net-5.0

Reason2: <Source> tag has a different namespace than the doc itself and so the query is looking in the wrong namespace.

Solution:

XNamespace ns = "http://www.acm.nl/DataModel/2018/09";
var element = xdoc.Descendants(ns + "Source").FirstOrDefault();

See https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xcontainer.descendants?view=net-5.0 which is searching for children including their children.

If you expect a node to exist, I'd also recommend to use First() instead of FirstOrDefault() . This way you'll get an exception that would have shown you the reason for your problem.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM