读书人

C# 解析XML,该如何处理

发布时间: 2012-04-15 18:39:21 作者: rapoo

C# 解析XML
大家好,请教大家一个问题,有XML文件数据,现要对其解析,并将解析结果绑定在datagridview控件里面。这里面有个需求,请大家帮我分析下。

HTML code
<?xml version="1.0" encoding="utf-16"?><items>  <totalResults>404</totalResults>  <Rows>    <orderCode>SC12031900028</orderCode>    <orderCode_item>      <Item>        <treasuryCoding>5</treasuryCoding>        <orderCode>SC12031900028</orderCode>        <consignmentBrand>999999</consignmentBrand>        <productId>LE-42S35FW</productId>        <productName>Pangoo42寸LED 3D电视LE-42S35FW-含挂架</productName>        <specification>42寸 3D</specification>        <orderQuantity>1</orderQuantity>        <shipmentsIn>1</shipmentsIn>        <isCancel />        <isScheduled />        <salesPrice>0.0000</salesPrice>        <itemStats>10</itemStats>        <date>2012/3/19 0:00:00</date>        <returnNum />        <purchasePrice>3117.0000</purchasePrice>        <returnsNum>0</returnsNum>        <returnsNum_Arr>0</returnsNum_Arr>        <weight>19.50</weight>        <timeInventory>0</timeInventory>        <inspection_Num />        <barcode>06949791500716</barcode>        <barcode1 />        <refundRecord />        <unitPrice>0.0000</unitPrice>        <totalPrice>0.0000</totalPrice>        <gifts_Num />        <totalFifoCost />        <digitalAndLibrary />      </Item>      <Item>        <treasuryCoding>5</treasuryCoding>        <orderCode>SC12031900028</orderCode>        <consignmentBrand>999999</consignmentBrand>        <productId>SU12030900019</productId>        <productName>42S35一年延保</productName>        <specification>42S35一年延保</specification>        <orderQuantity>1</orderQuantity>        <shipmentsIn>1</shipmentsIn>        <isCancel />        <isScheduled />        <salesPrice>0.0000</salesPrice>        <itemStats>10</itemStats>        <date>2012/3/19 0:00:00</date>        <returnNum />        <purchasePrice>0.0000</purchasePrice>        <returnsNum>0</returnsNum>        <returnsNum_Arr>0</returnsNum_Arr>        <weight>0.00</weight>        <timeInventory>0</timeInventory>        <inspection_Num />        <barcode>TM12030900019</barcode>        <barcode1 />        <refundRecord />        <unitPrice>0.0000</unitPrice>        <totalPrice>0.0000</totalPrice>        <gifts_Num />        <totalFifoCost />        <digitalAndLibrary />      </Item>    </orderCode_item>  </Rows></items>


现在我要取xml里面的<Item></Item>里面的字段‘orderCode’‘productId’‘productName’‘orderQuantity’‘totalPrice’在datagridview显示。一个<Item></Item>在datagridview里显示一行数据,上述xml有两个<Item></Item>,请教如何将其显示两行数据?

下面是我解析的部分逻辑代码,请高手指正!

C# code
foreach (XmlNode node in xml.ChildNodes)            {                if (node.Name == "items")                {                    foreach (XmlNode node1 in node.ChildNodes)                    {                        if (node1.Name == "Rows")                        {                            foreach (XmlNode node2 in node1.ChildNodes)                            {                                if (node2.Name == "orderCode_item")                                {                                    foreach (XmlNode node3 in node2.ChildNodes)                                    {                                        if (node3.Name == "Item")                                        {                                            foreach (XmlNode node4 in node3.ChildNodes)                                            {                                                switch (node4.Name)                                                {                                                    case "orderCode":                                                        orderCode = node4.InnerText;                                                        break;                                                    case "productId":                                                        productId = node4.InnerText;                                                        break;                                                    case "productName":                                                        productName = node4.InnerText;                                                        break;                                                    case "orderQuantity":                                                        orderQuantity=node4.InnerText;                                                        break;                                                    case "totalPrice":                                                        totalPrice = node4.InnerText;                                                        break;                                                }                                            }                                        }                                    }                                }                            } 



我这个结果是只返回第二个<Item></Item>的数据值。

[解决办法]
你妹,,,这么多曾foreach,莫非你就是传说中的要你命3000
[解决办法]
为Item写一个类,把需要解析得到的元素写成属性。
具体看看这个
[解决办法]
http://topic.csdn.net/u/20111019/11/b257dddd-029a-436d-883b-6241051fca70.html
[解决办法]
这个直接用dataset.readxml就可以了

读出来后,运行下个断点,在vs里面直接用dataset可视化调试器,看看有那些表,表结构如何就可以了

这种方式对于这种 xml结构已经固定下来的东西可能是最简单的直白的操作了
[解决办法]
C# code
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Xml;namespace TestXml{    class Program    {        static void Main(string[] args)        {            XmlElement theBook = null;            XmlElement theElement = null;            XmlElement root = null;            XmlDocument xmlDoc = new XmlDocument();            try            {                xmlDoc.Load("book.xml");                //xmlDoc.LoadXml("<item><name>wrench</name></item>");                root = xmlDoc.DocumentElement;                // ---新建一本书开始 ----                theBook = xmlDoc.CreateElement("book");                theBook.SetAttribute("id", "B01");                 theElement = xmlDoc.CreateElement("name");                theElement.InnerText = "新书";                theBook.AppendChild(theElement);                theElement = xmlDoc.CreateElement("price");                theElement.InnerText = "20";                theBook.AppendChild(theElement);                theElement = xmlDoc.CreateElement("memo");                theElement.InnerText = "新书更好看...";                theBook.AppendChild(theElement);                root.AppendChild(theBook);                Console.Out.WriteLine("---新建一本书开始---");                Console.Out.WriteLine(xmlDoc.OuterXml);                //下面对 三国演义做一些修改                //查询找 《三国演义》 --                theBook = (XmlElement)root.SelectSingleNode("/books/book[name='三国演义']") ;                Console.Out.WriteLine("---  查找《三国演义》 ----");                 Console.Out.WriteLine(theBook.OuterXml);                //修改这本书的 属性                theBook.GetElementsByTagName("price").Item(0).InnerText = "90";//getElementsByTagName返回的是NodeList,所以要跟上item(0)                 // 根据节点属性删除节点                theBook = (XmlElement)root.SelectSingleNode("/books/book[@id='B06']");                if (theBook != null)                {                    Console.Out.WriteLine("---删除id 为 B06的书籍---");                    Console.Out.WriteLine(theBook.OuterXml);                    theBook.ParentNode.RemoveChild(theBook);                }                else {                    Console.Out.WriteLine("未查找到指定的节点...");                }                /*                //---将价格低于20的书籍删除掉---                XmlNodeList someBooks = root.SelectNodes("/books/book[price<20]");                Console.Out.WriteLine("删除所有价格低于20的书籍.");                Console.Out.WriteLine("---符合条件的书籍有 " + someBooks.Count + " 本。---") ;                for (int i = 0; i < someBooks.Count; i++) {                    someBooks.Item(i).ParentNode.RemoveChild(someBooks.Item(i));                }                Console.Out.WriteLine("---删除后的XML---");                Console.Out.WriteLine(xmlDoc.OuterXml);                //---将名字=777---                XmlNodeList someBooks1 = root.SelectNodes("/books/book[name='777']");                Console.Out.WriteLine("删除名字为777的书籍.");                Console.Out.WriteLine("---符合条件的书籍有 " + someBooks1.Count + " 本。---");                for (int i = 0; i < someBooks1.Count; i++)                {                    someBooks1.Item(i).ParentNode.RemoveChild(someBooks1.Item(i));                }                Console.Out.WriteLine("---删除后的XML---");                Console.Out.WriteLine(xmlDoc.OuterXml);                */                XmlNodeList someBooks = root.SelectNodes("/books/book[contains(name,'77')]");                Console.Out.WriteLine("---符合条件的书籍有 " + someBooks.Count + " 条. ---");                xmlDoc.Save("book.xml");                Console.In.Read();            }catch (Exception e) {                Console.Out.Write(e.Message);                Console.In.Read();            }        }    }} 

读书人网 >C#

热点推荐