Home Backend Development C#.Net Tutorial C# basic series: Linq to Xml reading and writing xml

C# basic series: Linq to Xml reading and writing xml

Feb 07, 2017 pm 03:47 PM
c# xml

前言:xml的操作方式有多种,但要论使用频繁程度,博主用得最多的还是Linq to xml的方式,觉得它使用起来很方便,就用那么几个方法就能完成简单xml的读写。之前做的一个项目有一个很变态的需求:C#项目调用不知道是什么语言写的一个WebService,然后添加服务引用总是失败,通过代理的方式动态调用也总是报错,最后没办法,通过发送原始的WebRequest请求直接得到对方返回的一个xml文件。注意过webservice的wsdl文件的朋友应该知道这个是系统生成的xml文件,有点复杂,研究了半天终于能正常读写了。今天在这里和大家分享下。

1、介绍之前,首先回顾下Linq to xml的方式读写简单xml的方法

(1)读取xml

?xml version="1.0" encoding="utf-8"?>

<BizADsList>

  <adData aid="1" image="baidu.jpg" link="www.baidu.com" title="百度"/>

  <adData aid="2" image="qq.jpg" link="www.qq.com" title="腾讯"/>

</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 = a.Attribute("image").Value,

                         link = a.Attribute("link").Value,

                         title = a.Attribute("title").Value

                     };

            string s = "";

            foreach (var a in ad)

                s += a.image;
Copy after login

(2)写xml

   /// <summary>
        /// 根据得到的Document集合生成XML
        /// </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(CSpiderConst.XML_ELE_ROOT);

                //1.构造Device节点
                XElement xDevice = new XElement(CSpiderConst.XML_ELE_DEVICE);

                //2.构造NE节点
                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);
                }
                //这里增加一个<Item name=&#39;NewRate&#39;>和<Item name=&#39;SpiderTimeEx&#39;>节点用来保存当前这次的利用率和当次的采集时间
                AddNewRateAndSpiderTime(strSpiderTime, strNewRate, xNE);
                xDevice.Add(xNE);

                //3.循环构造BD节点并添加到Device节点中
                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.保存到采集器本地,以服务器的时间和网元的AssetID来命名
                var strDirectoryPath = Path.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("保存XML失败");
            }
        }
Copy after login

通过XDocument、XElement对象和Element()、Elements()两个方法能完成大部分xml文件的操作。

2、进入今天的正题:读写带命名空间的xml文件。

首先来看一段xml

<?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:UseCurrentLocale="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:element>
  </xs:schema>
</DataSet>
Copy after login

第一次看到这个文件确实让人萌神了,比如需要取一个msdata:IsDataSet=”true”这个属性,该怎么取…


解析之前,先来分析下这段xml,这段里面有一个xmlns属性,这个属性是每一个标签自带的属性,不信你可以新建一个xml文件,然后在任何一个标签里面输入xmlns属性,后面都会出来很多的系统自带的命名空间。这个属性表示所属标签在哪个命名空间下面,所以在取的时候要带上这个命名空间。


先来看看解析的代码:

var strPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"data\test.xml");
var oRoot = XDocument.Load(strPath);
//取DataSet标签
var oDataSet = oRoot.Element(XName.Get("DataSet", "http://WebXml.com.cn/"));
//取schema标签
var oSchema = oDataSet.Element(XName.Get("schema", "http://www.w3.org/2001/XMLSchema"));
//取element标签
var oElement = oSchema.Element(XName.Get("element", "http://www.w3.org/2001/XMLSchema"));//这两个节点都是以xs打头,所以命名空间都是xs的命名空间
//取element标签下面的IsDataSet属性
var oElementValue = oElement.Attribute(XName.Get("IsDataSet", "urn:schemas-microsoft-com:xml-msdata"));
//取aa标签
var oAA = oSchema.Element(XName.Get("aa", "urn:schemas-microsoft-com:xml-msdata"));
Copy after login

我们来解析下几个关键的地方:

(1)我们来解析下

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

这一句,最前面的”xs”表示标签所属命名空间的变量,xmlns:xs=”http://www.w3.org/2001/XMLSchema”这个表示xs这个命名空间的值。所以要得到schema这个标签需要带上命名空间var oSchema = oDataSet.Element(XName.Get(“schema”, “http://www.w3.org/2001/XMLSchema”));这个标签还定义了另一个命名空间xmlns:msdata=”urn:schemas-microsoft-com:xml-msdata”。

(2)再来看看aa标签

<msdata:aa>
      test
 </msdata:aa>
Copy after login

msdata就是上面schema标签里面定义的另一个命名空间,表示aa标签属于msdata命名空间下面。

(3)再看来看属性的取法:

<xs:element name="getRegion" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
Copy after login

如果要取msdata:IsDataSet=”true”,由于这个属性也带有命名空间,所以取属性时也要加上命名空间了。所以需要这样取。

var oElementValue = oElement.Attribute(XName.Get(“IsDataSet”, “urn:schemas-microsoft-com:xml-msdata”));
Copy after login

现在大伙们应该对这种xml有一个更加清晰的认识了吧。其实一般情况下这种场景比较少见,因为这么复杂的xml一般是由引用服务时代理对象去解析的。但如果真的有这么变态的需求我们也不用担心了。在此记录下,以后如果大家遇到希望能节约大伙的时间。

以上就是C#基础系列:Linq to Xml读写xml的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

How to change the format of xml How to change the format of xml Apr 03, 2025 am 08:42 AM

There are several ways to modify XML formats: manually editing with a text editor such as Notepad; automatically formatting with online or desktop XML formatting tools such as XMLbeautifier; define conversion rules using XML conversion tools such as XSLT; or parse and operate using programming languages ​​such as Python. Be careful when modifying and back up the original files.

C# vs. C  : History, Evolution, and Future Prospects C# vs. C : History, Evolution, and Future Prospects Apr 19, 2025 am 12:07 AM

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

How to convert xml into word How to convert xml into word Apr 03, 2025 am 08:15 AM

There are three ways to convert XML to Word: use Microsoft Word, use an XML converter, or use a programming language.

What are the benefits of multithreading in c#? What are the benefits of multithreading in c#? Apr 03, 2025 pm 02:51 PM

The advantage of multithreading is that it can improve performance and resource utilization, especially for processing large amounts of data or performing time-consuming operations. It allows multiple tasks to be performed simultaneously, improving efficiency. However, too many threads can lead to performance degradation, so you need to carefully select the number of threads based on the number of CPU cores and task characteristics. In addition, multi-threaded programming involves challenges such as deadlock and race conditions, which need to be solved using synchronization mechanisms, and requires solid knowledge of concurrent programming, weighing the pros and cons and using them with caution.

How to open xml format How to open xml format Apr 02, 2025 pm 09:00 PM

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.

How to convert xml to json How to convert xml to json Apr 03, 2025 am 09:09 AM

Methods to convert XML to JSON include: writing scripts or programs in programming languages ​​(such as Python, Java, C#) to convert; pasting or uploading XML data using online tools (such as XML to JSON, Gojko's XML converter, XML online tools) and selecting JSON format output; performing conversion tasks using XML to JSON converters (such as Oxygen XML Editor, Stylus Studio, Altova XMLSpy); converting XML to JSON using XSLT stylesheets; using data integration tools (such as Informatic

See all articles