C # Reading Xml files

Source: Internet
Author: User

In C #, you can use the XmlDocument class to operate Xml files.

For example, to read the following Xml file

      
  
          25     
       
  
          56     
     
 

The program is as follows:

 
 

XmlDocument doc = new XmlDocument (); doc. load ("config. xml "); // load the Xml file XmlElement rootElem = doc. documentElement; // get the root node XmlNodeList personNodes = rootElem. getElementsByTagName ("person"); // gets the foreach (XmlNode node in personNodes) {string strName = (XmlElement) node) of the person subnode set ). getAttribute ("name"); // obtain the name attribute value Console. writeLine (strName); XmlNodeList subAgeNodes = (XmlElement) node ). getElementsByTagName ("age"); // gets the age sub-XmlElement set if (subAgeNodes. count = 1) {string strAge = subAgeNodes [0]. innerText; Console. writeLine (strAge );}}


XmlElement inherits from XmlNode.

XmlElement has GetAttribute () & GetElementsByTagName () and other methods, while XmlNode does not

Whether the ChildNodes attribute of XmlNode or the GetElementsByTagName () method of XmlElement is used, XmlNodeList is obtained.

So here there is a question about the type of XmlNode in the obtained XmlNodeList.

It can be determined based on the NodeType attribute of XmlNode.

If it is equal to XmlNodeType. Element, it can be converted to XmlElement to use the XmlElement method.

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.