How to read complex Xml and use

Source: Internet
Author: User
Tags foreach object model

Read complex Xml (with namespace) using Linq to xml)

Xml can be operated in a variety of ways, but the frequently used method is the most frequently used method by bloggers, which is convenient to use, you can read and write simple xml in a few ways. The previous project had a very abnormal requirement: C # Project calls do not know the language of a WebService, and then add service references always fail, an error is always reported during dynamic calling through a proxy. In the end, the xml file returned by the other party is directly obtained by sending the original WebRequest request. Those who have noticed the wsdl file of webservice should know that this is an xml file generated by the system, which is a bit complicated. After studying it for a long time, they can finally read and write normally. I would like to share with you today.

1. Before introduction, let's first review the method of writing and writing simple xml using the method of Linq to xml.

(1) read xml


<? Xml version = "1.0" encoding = "UTF-8"?> <BizADsList> <adData aid = "1" image = "baidu.jpg" link = "www.baidu.com" title = "Baidu"/> <adData aid = "2" image = "qq.jpg" link = "www.qq.com" title = "Tencent"/> </BizADsList>
Var strPath = Path. combine (AppDomain. currentDomain. baseDirectory, @ "data \ test. xml "); XDocument adList = XDocument. load (strPath); var ad = from a in adList. descendants ("BizADsList "). elements ("adData") select new {image =. attribute ("image "). value, link =. attribute ("link "). value, title =. attribute ("title "). value}; string s = ""; foreach (var a in ad) s + =. image;





(2) write xml

/// <Summary> /// generate XML based on the obtained Document set /// </summary> /// <param name = "lstDocumentBD"> </param> // /<param name = "docNE"> </param> // <param name = "strSpiderTime"> </param> // <param name = "strNewRate"> </param> private static void SaveXmlByLstDocument (List <Document> lstDocumentBD, document docNE, string strSpiderTime, string strNewRate) {try {XDocument xDoc = new XDocument (); XElement xRoot = new XElement (CS PiderConst. XML_ELE_ROOT); // 1. construct the Device node XElement xDevice = new XElement (CSpiderConst. XML_ELE_DEVICE); // 2. construct the XElement xNE = new XElement (CSpiderConst. XML_ELE_NE); foreach (var oDocNE in docNE) {XElement xItem = new XElement (CSpiderConst. XML_ELE_ITEM, new XAttribute (CSpiderConst. XML_PROP_NAME, oDocNE. key), oDocNE. value); xNE. add (xItem) ;}// Add <Item name = 'newrate'> and <Item name = 'spidertimeex '> The node is used to save the current utilization rate and the current collection time AddNewRateAndSpiderTime (strSpiderTime, strNewRate, xNE); xDevice. add (xNE); // 3. construct the BD node cyclically and add it to the Device node. foreach (var oDocument in lstDocumentBD) {XElement xBD = new XElement (CSpiderConst. XML_ELE_BD); foreach (var oDocBD in oDocument) {XElement xItem = new XElement (CSpiderConst. XML_ELE_ITEM, new XAttribute (CSpiderConst. XML_PROP_NAME, oDocBD. key), oDocBD. value); xBD. add (xItem );} AddNewRateAndSpiderTime (strSpiderTime, strNewRate, xBD); xDevice. add (xBD);} xRoot. add (xDevice); xDoc. add (xRoot); // 4. save it to the local device of the collector and name var strDirectoryPath = Path based on the server time and network element AssetID. combine (AppDomain. currentDomain. baseDirectory, "ReportFailed \"); if (! Directory. exists (strDirectoryPath) {Directory. createDirectory (strDirectoryPath);} xDoc. save (strDirectoryPath + docNE [TBLDeviceLCBB. PROP_ASSETID] + "_" + strSpiderTime. replace (":", "_") + ". xml ");} catch {CLogService. instance. debug ("failed to save XML ");}}



You can perform operations on most xml files using the XDocument, XElement object, Element (), and Elements () methods.

2. Enter the subject of today: read and write xml files with namespaces.

First, let's look at an xml section.

<? Xml version = "1.0" encoding = "UTF-8"?> <DataSet xmlns = "http://WebXml.com.cn/"> <xs: schema xmlns = "" xmlns: xs = "http://www.w3.org/2001/XMLSchema" xmlns: msdata = "urn: schemas-microsoft-com: xml-msdata "id =" getRegion "> <msdata: aa> test </msdata: aa> <xs: element name =" getRegion "msdata: IsDataSet =" true "msdata: usecuritylocale = "true"> <xs: element name = "Province"> <xs: sequence> <xs: element name = "RegionID" type = "xs: string "minOccurs =" 0 "/> <xs: element name =" RegionName "type =" xs: string "minOccurs =" 0 "/> </xs: sequence> </xs: element> </xs: schema> </DataSet>



The first time I saw this file, it was really amazing. For example, how do I obtain the attribute "msdata: IsDataSet =" true...

Before parsing, first analyze this section of xml, <DataSet xmlns = "http://WebXml.com.cn/"> This section contains an xmlns attribute, this attribute is the attributes of each tag, if you don't believe it, you can create an xml file and enter the xmlns attribute in any tag. Many built-in namespaces will be created later. This attribute indicates the namespace under which the label belongs. Therefore, this namespace must be included when obtaining the tag.

Let's take a look at the parsed code:

Var strPath = Path. combine (AppDomain. currentDomain. baseDirectory, @ "data \ test. xml "); var oRoot = XDocument. load (strPath); // Obtain the DataSet tag var oDataSet = oRoot. element (XName. get ("DataSet", "http://WebXml.com.cn/"); // Get schema label var oSchema = oDataSet. element (XName. get ("schema", "http://www.w3.org/2001/XMLSchema"); // Obtain the element tag var oElement = oSchema. element (XName. get ("element", "http://www.w3.org/2001/XMLSchema"); // both nodes are headers with xs, therefore, all namespaces are named by xs. // take the IsDataSet attribute var oElementValue = oElement under the element tag. attribute (XName. get ("IsDataSet", "urn: schemas-microsoft-com: xml-msdata"); // Obtain the aa tag var oAA = oSchema. element (XName. get ("aa", "urn: schemas-microsoft-com: xml-msdata "));




Let's analyze several key points:

(1) Let's analyze

<Xs: schema xmlns = "" xmlns: xs = "http://www.w3.org/2001/XMLSchema" xmlns: msdata = "urn: schemas-microsoft-com: xml-msdata" id = "getRegion">



In this sentence, the prefix "xs" represents the variable to which the label belongs to the namespace, and xmlns: xs = "http://www.w3.org/2001/XMLSchema" represents the value of the xs namespace. Therefore, to obtain the schema label, we need to add the namespace var oSchema = oDataSet. element (XName. get ("schema", "http://www.w3.org/2001/XMLSchema"); this tag also defines another namespace xmlns: msdata = "urn: schemas-microsoft-com: xml-msdata ".

(2) Let's take a look at the aa tag.

<Msdata: aa> test </msdata: aa>



Msdata is another namespace defined in the schema tag above, indicating that the aa tag belongs to the msdata namespace.

(3) let's look at the method of getting the property:

<Xs: element name = "getRegion" msdata: IsDataSet = "true" msdata: usecuritylocale = "true">



If you want to get msdata: IsDataSet = "true", because this attribute also has a namespace, you must add a namespace when getting the attribute. So we need to take it like this.

Var oElementValue = oElement. Attribute (XName. Get ("IsDataSet", "urn: schemas-microsoft-com: xml-msdata "));


Now everyone should have a clearer understanding of this xml. In fact, this scenario is rare in general, because such complex xml is generally parsed by the rational object in the era of reference services. But we don't have to worry about such abnormal demands. In this record, if you want to save your time in the future.


Summary of using Linq to js

1. What is Linq to js: C #3.0 introduces the. Net special new feature: Linq. With Linq, programmers no longer have to worry about set operations. Likewise, Linq to js is, of course, a technical framework for operating front-end set variables.

2. How to use it: because it is a front-end framework, you know that you only need to reference a js file. Please refer to the following link for more information: http://jslinq.codeplex.com/.there are files and demos. There are two main ways to use: Method 1. Directly reference js files; Method 2. Use Nuget Package to install Linq to js. On the PM installation console, enter Install-Package jslinq.

This article describes common methods by writing lamada expressions in Linq to js. The downloaded files are shown in the figure below.

We only need to reference the linq. js file.

(1) conditional query: Where

Var myList = [{Name: "Jim", Age: 20}, {Name: "Kate", Age: 21}, {Name: "Lilei", Age: 18 }, {Name: "John", Age: 14}, {Name: "LinTao", Age: 25}]; var arrRes = Enumerable. from (myList ). where ("x => x. name = 'Jim '"). toArray ();





The result of arrRes is [{"Name": "Jim", "Age": 20}].

Let's take a look at the prototype of writing Lamada expressions:

Var arrRes = Enumerable. From (myList). Where (function (I) {return I. Name = 'Jim ';});

Parameter I is the entity model in the corresponding set. The return type is bool. Is there a definition similar to the Where extension function in C #: public static IEnumerable <TSource> Where <TSource> (this IEnumerable <TSource> source, Func <TSource, bool> predicate ); the Func <TSource, bool> predicate parameter is an anonymous delegate. You need to input the object model TSource and then return the bool type. In fact, I feel that the use of linq to js is defined in c.

 

(2) Select conditions: Select

Var myList = [{Name: "Jim", Age: 20}, {Name: "Kate", Age: 21}, {Name: "Lilei", Age: 18 }, {Name: "John", Age: 14}, {Name: "LinTao", Age: 25}]; var arrRes = Enumerable. from (myList ). select ("x => x. age * 10 "). toArray ();




ArrRes returns [200,210,180,140,250].

 

(3) sorting and deduplication: OrderBy and Distinct


Var myList = [{Name: "Jim", Age: 20}, {Name: "Kate", Age: 21}, {Name: "Lilei", Age: 18 }, {Name: "John", Age: 14}, {Name: "LinTao", Age: 25}]; var arrRes = Enumerable. from (myList ). orderBy ("x => x. age "). toArray (); // OrderByDescending () in descending order ()



The result is sorted by Age.

Var myList = [{Name: "Jim", Age: 20}, {Name: "Kate", Age: 20}, {Name: "Lilei", Age: 20 }, {Name: "John", Age: 14}, {Name: "LinTao", Age: 25}]; var arrRes = Enumerable. from (myList ). distinct ("x => x. age "). toArray ();





The number of result sets is 3: [{Name: "Jim", Age: 20}, {Name: "John", Age: 14}, {Name: "LinTao", Age: 25}].

 

(4) traversal: ForEach

Var myList = [{Name: "Jim", Age: 20}, {Name: "Kate", Age: 20}, {Name: "Lilei", Age: 20 }, {Name: "John", Age: 14}, {Name: "LinTao", Age: 25}]; Enumerable. from (myList ). forEach (function (value, index) {document. write ("value =" + value + ", index =" + index );});




Obviously, there are two parameters: one is the value and the other is the current index.
 

(5) unique objects: First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault

Var myList = [{Name: "Jim", Age: 20}, {Name: "Kate", Age: 20}, {Name: "Lilei", Age: 20 }, {Name: "John", Age: 14}, {Name: "LinTao", Age: 25}]; var arrRes = Enumerable. from (myList ). firstOrDefault ("x => x. age> 18 ");





Other usage is similar to this. There is nothing to say about it.


(6) Skip and Take

Enumerable. range (1, 10 ). skip (5) // result [6, 7, 8, 9, 10] Enumerable. range (1, 10 ). take (5) // result [1, 2, 3, 4, 5]



(7) intersection, difference, and merge

Var array1 = [1,412, 5,412, 7,310, 7]; var array2 = [,]; Enumerable. from (array1 ). except t (array2) // result 3,412, 1var array1 = [1,412, 5,412, 7,310, 7]; var array2 = [20, 12, 5,]; Enumerable. from (array1 ). intersect (array2) // Result 5, 7var array1 = [1,412, 5,412, 7,310, 7]; var array2 = [20, 12, 5,]; Enumerable. from (array1 ). union (array2) // The result is all values in the two result sets and is automatically de-duplicated.



 

Of course, there are other uncommon methods. If you are interested, you can view the document. In fact, there is also a way to support jquery writing in linq to js. As follows:

Enumerable. range (1, 10 ). where ("$ % 2 = 0") // equivalent to Enumerable. range (1, 10 ). where ("x => x % 2 = 0 ")



However, when referencing a file, you must reference the file jquery. linq. js. It means that the writing method is different, and the effect is the same. Which one is a habit problem. Bloggers prefer to write lamada statements because they can be consistent with C # statements.

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.