How to set an XML element attribute using linq in xml in c #

I have an xml file like

    <Root>
       <Steps>
            <Step Test="SampleTestOne" Status="Fail" /> 
            <Step Test="SampleTestTwo" Status="Fail" /> 
       </Steps>
    </Root>

I need to change or overwrite the value of the Status attribute in the Step element.

Now I am using XmlDocument for this as

        XmlDocument XDoc = new XmlDocument();
        XDoc.Load(Application.StartupPath + "\\Sample.xml");
        XmlNodeList NodeList = XDoc.SelectNodes("//Steps/Step");
        foreach (XmlNode Node in NodeList)
        {
            XmlElement Elem = (XmlElement)Node;
            String sTemp = Elem.GetAttribute("Test");
            if (sTemp == "SampleTestOne")
                Elem.SetAttribute("Status", "Pass");

        }

I need to find an item and update status

is there any way to do this using XDocumentin C #

Thanks in advance

+3
source share
2 answers
string filename = @"C:\Temp\demo.xml";
XDocument document = XDocument.Load(filename);

var stepOnes = document.Descendants("Step").Where(e => e.Attribute("Test").Value == "SampleTestOne");
foreach (XElement element in stepOnes)
{
    if (element.Attribute("Status") != null)
        element.Attribute("Status").Value = "Pass";
    else
        element.Add(new XAttribute("Status", "Pass"));
}

document.Save(filename); 
+4
source

You can use this code:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFile);
XmlNode node = xmlDoc.SelectSingleNode("Root/Steps/Step");
node.Attributes["Status"].Value = "True";
xmlDoc.Save(xmlFile);
+2
source

Source: https://habr.com/ru/post/1751586/


All Articles