Modify XML existing content in C#

前端 未结 4 1288
青春惊慌失措
青春惊慌失措 2020-11-29 06:04

Purpose: I plan to Create a XML file with XmlTextWriter and Modify/Update some Existing Content with XmlNode SelectSingleNode(), node.ChildNode[?].InnerText = someting, etc.

相关标签:
4条回答
  • 2020-11-29 06:29

    Using LINQ to xml if you are using framework 3.5

    using System.Xml.Linq;
    
    XDocument xmlFile = XDocument.Load("books.xml"); 
    var query = from c in xmlFile.Elements("catalog").Elements("book")    
                select c; 
    foreach (XElement book in query) 
    {
        book.Attribute("attr1").Value = "MyNewValue";
    }
    xmlFile.Save("books.xml");
    
    0 讨论(0)
  • 2020-11-29 06:30

    Forming a XML file

    XmlTextWriter xmlw = new XmlTextWriter(@"C:\WINDOWS\Temp\exm.xml",System.Text.Encoding.UTF8);
    xmlw.WriteStartDocument();            
    xmlw.WriteStartElement("examtimes");
    xmlw.WriteStartElement("Starttime");
    xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
    xmlw.WriteEndElement();
    xmlw.WriteStartElement("Changetime");
    xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
    xmlw.WriteEndElement();
    xmlw.WriteStartElement("Endtime");
    xmlw.WriteString(DateTime.Now.AddHours(1).ToString());
    xmlw.WriteEndElement();
    xmlw.WriteEndElement();
    xmlw.WriteEndDocument();  
    xmlw.Close();           
    

    To edit the Xml nodes use the below code

    XmlDocument doc = new XmlDocument(); 
    doc.Load(@"C:\WINDOWS\Temp\exm.xml"); 
    XmlNode root = doc.DocumentElement["Starttime"]; 
    root.FirstChild.InnerText = "First"; 
    XmlNode root1 = doc.DocumentElement["Changetime"]; 
    root1.FirstChild.InnerText = "Second"; 
    doc.Save(@"C:\WINDOWS\Temp\exm.xml"); 
    

    Try this. It's C# code.

    0 讨论(0)
  • 2020-11-29 06:30

    The XmlTextWriter is usually used for generating (not updating) XML content. When you load the xml file into an XmlDocument, you don't need a separate writer.

    Just update the node you have selected and .Save() that XmlDocument.

    0 讨论(0)
  • 2020-11-29 06:48

    Well, If you want to update a node in XML, the XmlDocument is fine - you needn't use XmlTextWriter.

    XmlDocument doc = new XmlDocument();
    doc.Load("D:\\build.xml");
    XmlNode root = doc.DocumentElement;
    XmlNode myNode = root.SelectSingleNode("descendant::books");
    myNode.Value = "blabla";
    doc.Save("D:\\build.xml");
    
    0 讨论(0)
提交回复
热议问题