开发者

How to parse and update xml file using xmltextreader or xmlreader

Hi i have the following code to read the xml file and change the value of particular node ,but i want to do the same using xmltextreader or xmlreader, i am trying to avoid the statement doc.Save(System.Web.HttpContext.Current.Server.MapPath("Data/Examp开发者_如何转开发le.xml")); , which has a direct reference to my physical file.

XmlDocument doc = new XmlDocument();
                   string xmlFile = System.Web.HttpContext.Current.Server.MapPath("Data/Example.xml");
                   doc.Load(xmlFile);
                   XmlNodeList xmlnode = doc.GetElementsByTagName("value");
                   xmlnode[0].ChildNodes[0].Value = 23;
 doc.Save(System.Web.HttpContext.Current.Server.MapPath("Data/Example.xml"));


Well something's going to have to have a reference to the file. However, you could easily change your code to simply accept a Stream (which would have to be readable, writable and seekable):

private static void ChangeDocument(Stream stream)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(stream);
    XmlNodeList xmlnode = doc.GetElementsByTagName("value");
    xmlnode[0].ChildNodes[0].Value = 23;
    stream.Position = 0;
    doc.Save(stream);
    stream.SetLength(stream.Position); // Truncate the file if it was longer
}

It's somewhat ugly, admittedly...

Of course you could always pass in the filename itself - your MapPath call would still be in a higher level method, which may be all you're trying to achieve:

private static void ChangeDocument(string filename)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(filename);
    XmlNodeList xmlnode = doc.GetElementsByTagName("value");
    xmlnode[0].ChildNodes[0].Value = 23;
    doc.Save(filename);
}

One final aside - if you're using .NET 3.5 or higher, I'd strongly recommend using LINQ to XML as a rather nicer XML API.


You can not write or update XML data using XmlTextReader or XmlReader ansectors, use XmlTextWriter or XmlWriter ancestors, ot XmlSerializer.Serialize(..) method as alternative.

You can not avoid the statement and alike,

doc.Save(System.Web.HttpContext.Current.Server.MapPath("Data/Example.xml"));

which has a direct reference to your physical file, because you have to write the changed nodes back to the origin file again, otherwize you have to switch your system from using file-based approach (ASP.NET web site using file-based data storage) to database-driven approach (ASP.NET web site using the database server).

As alternative, use your own XML data in your SQL server, then load and update it using EF of ORM.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜