Update value in xml file

前端 未结 4 2097
暖寄归人
暖寄归人 2021-02-14 16:26

I have a xml-file:



  
    
    
    &         


        
相关标签:
4条回答
  • 2021-02-14 16:52
    XElement t = XElement.Load("filePath");
    t.Element("level").Element("node1").Value = "";
    t.Element("level").Element("node2").Value = "";
    t.Element("level").Element("node3").Value = "";
    t.Save("filePath");
    
    0 讨论(0)
  • 2021-02-14 16:59

    Here you go:

    XmlDocument xmldoc = new XmlDocument();
    xmldoc.LoadXml(@"
        <root>
            <level>
                <node1 />
                <node2 />
                <node3 />
            </level>
        </root>");
    XmlElement node1 = xmldoc.SelectSingleNode("/root/level/node1") as XmlElement;
    if (node1 != null)
    {
        node1.InnerText = "something"; // if you want a text
        node1.SetAttribute("attr", "value"); // if you want an attribute
        node1.AppendChild(xmldoc.CreateElement("subnode1")); // if you want a subnode
    }
    
    0 讨论(0)
  • 2021-02-14 17:03

    Use AppendChild method to inser a child inside a node.

    yournode.AppendChild(ChildNode);
    

    link text

    0 讨论(0)
  • 2021-02-14 17:04
    //Here is the variable with which you assign a new value to the attribute
        string newValue = string.Empty 
        XmlDocument xmlDoc = new XmlDocument();
    
        xmlDoc.Load(xmlFile);
    
        XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element");
        node.Attributes[0].Value = newValue;
    
        xmlDoc.Save(xmlFile);
    

    Credit goes to Padrino

    How to change XML Attribute

    0 讨论(0)
提交回复
热议问题