Read simple XML files

Source: Internet
Author: User

If you have any questions, add the QQ group.14670545Discussion

I also don't like nested multi-layer XML. Of course, in some cases, this display is more straightforward and logical. The following uses a simple XML for example. The XML content is as follows (Name: createhtml. config ):

<?xml version="1.0" encoding="utf-8" ?><web>  <website key="0" value="title"/>  <website key="1" value="name"/>  <website key="2" value="url"/>  <website key="3" value="createDate"/>  <website key="4" value="desc"/>    <testAA key="fds" value="123" />  <testAA key="HH" value="123" />  <testAA key="RRE" value="123" />  <net>    <aspx key="c#" value="linq" />    <aspx key="f#" value="fn" />  </net></web>

Now I only want to get how to operate website items under the Web node. You only need to use the load method of xmldocument to reload the XML file in a path to the memory, and then use xmlnodelist for filtering.

Of course, when reading XML files, we will inevitably involve file operations, such as whether the XML in this path exists:

/// <Summary> /// check whether a file exists /// </Summary> /// <Param name = "filepath"> physical path of the file </param> /// <returns> </returns> private bool isexistfiles (string filepath) {try {If (system. io. file. exists (filepath) return true;} catch (exception ex) {Throw new exception (ex. message + "\ r \ n" + "may be other error: the file does not exist or access is prohibited! ");} Return false ;}

Next, we will create a config folder under the website's and Directory, which will be used for the configuration file. In this folder, we will create a new createhtml. config XML file. Then put a button on the page to read the XML:

<Div id = "div_test"> <% = AAAA %> </div> <br/> <form runat = "server" id = "form1"> <asp: button runat = "server" id = "btngetxml" text = "read XML file" onclick = "btngetxml_click"/> </form>

using System;using System.Xml;using System.Collections.Generic;
Public String AAAA = string. empty; // <summary> // read the XML file for testing /// </Summary> protected void btngetxml_click (Object sender, eventargs e) {dictionary <string, string> DIC = readconfig ("~ /Config/createhtml. config "," Web/website "); If (DIC = NULL) return; foreach (keyvaluepair <string, string> kV in DIC) aaaa + = "<br/>" + kv. key + ":" + kv. value ;} /// <summary> /// read the number of nodes in the configuration file. /// </Summary> /// <Param name = "path"> path of the configuration file </ param> /// <Param name = "nodename"> the node to be retrieved </param> private dictionary <string, string> readconfig (string path, string nodename) {dictionary <string, string> DIC = new Dictionary <string, string> (); string absopath = string. empty; // absolute path try {absopath = system. web. httpcontext. current. server. mappath (PATH); If (isexistfiles (absopath) {xmldocument XD = new xmldocument (); XD. load (absopath); xmlnodelist nodelist = XD. selectnodes (nodename); // obtain the set of corresponding nodes if (nodelist! = NULL & nodelist. count> 0) for (INT I = 0; I <nodelist. count; I ++) dic. add (nodelist. item (I ). attributes ["key"]. value, nodelist. item (I ). attributes ["value"]. value);} return DIC;} catch (exception ex) {Throw new exception (ex. message );}}

See the results:

To select the testaa item, you only need to modify the selectnodes object (Web/testaa ).

Note: I use dictionary storage, and the dictionary is the key-Value Pair keyvaluepair. The hash must be unique. Therefore, when you use the preceding method, the keys in XML cannot be duplicated, otherwise, an error is reported. Solution: 1. Modify the add method to ensure that the method is unique.

public class SafeDictionary<TKey, TValue>{private readonly object _Padlock = new object();private readonly Dictionary<TKey, TValue> _Dictionary = new Dictionary<TKey, TValue>();public bool ContainsKey(TKey key){return _Dictionary.ContainsKey(key);}public TValue this[TKey key]{get{return _Dictionary[key];}}public void Add(TKey key, TValue value){lock(_Padlock){_Dictionary.Add(key,value);}}}

2. Change the object storage, such as namevaluecollection.

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.