XML file modifies node attribute values (multiple methods) _ Practical Tips

Source: Internet
Author: User
XML File Contents:
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<subtitles>
<info>
<content> Latest Notice: 51 Holiday seven days! Please let the teachers know </content>
<speed>4</speed>
<color>red</color>
</info>
</subtitles>

C # code:
Copy Code code as follows:

XmlDocument xml = new XmlDocument ();
Xml. Load (context. Server.MapPath ("~/js/xmlfile.xml"));
XmlNode xn = XML. DocumentElement;
foreach (XmlNode node in xn. ChildNodes)
{
if (node. Name = = "Info")
{
node["Content"]. innertext = content;
node["Speed"]. InnerText = speed;
node["Color"]. innertext = color;
}
}
Xml. Save (context. Server.MapPath ("~/js/xmlfile.xml"));

Two other ways:
Modifies the attribute value of a node of an XML string as follows:
Copy Code code as follows:

XmlDocument doc = new XmlDocument ();
Doc. Loadxml ("<fsdlconfig username=\" ss\ "password=\" 134\ "/>");
XmlAttribute att = (xmlattribute) doc. selectSingleNode ("/fsdlconfig/@userName");
Console.WriteLine (Att. Value);
Att. Value = "Test";
String str = doc. OuterXml;

The value of the node username from the original "SS" to "Test", and then with Doc. OuterXml saves the modified XML as a string.
Another way
Copy Code code as follows:

XmlDocument doc = new XmlDocument ();
Doc. Loadxml ("<fsdlconfig username=\" ss\ "password=\" 134\ "/>");
XmlElement att = (xmlelement) doc. FirstChild;
Att. SetAttribute ("UserName", "Test");
String str = doc. OuterXml;
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.