Tuesday, April 5, 2011

Update programmatically xml with C#

i try to update xml without linq (i am using VC 2.0). My xml file format:


<schedule>
<id>0</id>
<name>yusuf</name>
<status>0</status>
</schedule>

AFTER UPDATE:

<schedule>
<id>0</id>
<name>yusuf</name>
<status>1</status>
</schedule>

but i do not have any idea update status =0 to status =1

From stackoverflow
  • You can do this with System.Xml.XmlDocument in any version of .NET (except Silverlight, where only XDocument exists):

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml); // or doc.Load(path)
        doc.SelectSingleNode("/schedule/status").InnerText = "1";
        string newXml = doc.OuterXml; // or doc.Save(path);
    
    xan : Just remember to check that SelectSingleNode() actually returns a node (check for null) or you will get an exception.
    Marc Gravell : Well, if we are expecting it to be there, an exception is reasonable -but yes, we could throw something more obvious "status node not found" or something.
    Kev : I am now waiting for the regular expression crowd to arrive to tell us how to do it properly :)
    Phsika : XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); // or doc.Load(path) Path error give me. Error Detail: "C:\\codes\\Schedule\\Schedule\\ScheduleTest\\ScheduleTest\\bin\\Debug/XmlFile/Schedules.xml"
    Marc Gravell : Then please verify that your xml file is valid. It sounds like it isn't.
    Marc Gravell : Note you should be using the doc.Load(path) variant for a file
  • Stuff your XML into XmlDocument, do the update and then save the result.

0 comments:

Post a Comment