tags:

views:

32

answers:

2

i've 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 attribute value of "Status" in the Step element.

Now i'm using XmlDocument for this like

        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 search the element and to update the status

is there any way to do this using XDocumentin c#

Thanks in advance

+2  A: 
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); 
Anthony Pegram
@ Anthony Pegram : Thank you. If no such attribute("Status") exist its throwing an exception. If no such attribute exist i need to create the attribute and then to add the value.Please Explain me this too
Pramodh
@Pramodh, edited in.
Anthony Pegram
A: 

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);
SageNS
He wants a Linq approach, I assume it's for learning purposes since he knows alternate ways.
Anthony Pegram
Oh, I missed it, thank you
SageNS