详解C#对XML、JSON等格式的解析

2019-12-30 15:09:52王振洲

一、C#对XML格式数据的解析

1、用XMLDocument来解析


XmlDocument xmlDocument = new XmlDocument(); 
xmlDocumentLoad("testxml"); 
 
//创建新节点  
XmlElement nn = xmlDocumentCreateElement("image"); 
nnSetAttribute("imageUrl", "jpg"); 
 
XmlNode node = xmlDocumentSelectSingleNode("content/section/page/gall/folder");//定位到folder节点 
nodeAppendChild(nn);//附加新节点 
 
//保存 
xmlDocumentSave("testxml"); 

2、用Linq to XML来解析

可以通过遍历,来获得你想要的节点的内容或属性


XElement root = XElementLoad("testxml"); 
foreach (XAttribute att in rootAttributes()) 
{ 
  rootAdd(new XElement(attName, (string)att)); 
} 
ConsoleWriteLine(root); 

3、附一个详细点的例子

比如要解析如下的xml文件,将其转化为Ilist对象。


<?xml version="0" encoding="utf-8"?> 
<Car> 
 <carcost> 
  <ID>20130821133126</ID> 
  <uptime>60</uptime> 
  <downtime>30</downtime> 
  <price>4</price> 
 </carcost> 
 <carcost> 
  <ID>20130821014316</ID> 
  <uptime>120</uptime> 
  <downtime>60</downtime> 
  <price>3</price> 
 </carcost> 
 <carcost> 
  <ID>20130822043127</ID> 
  <uptime>30</uptime> 
  <downtime>0</downtime> 
  <price>5</price> 
 </carcost> 
 <carcost> 
  <ID>20130822043341</ID> 
  <uptime>120以上!</uptime> 
  <downtime>120</downtime> 
  <price>2</price> 
 </carcost> 
</Car> 

在控制台应用程序中输入如下代码即可。


class Program 
{ 
  static void Main(string[] args) 
  { 
    IList<CarCost> resultList = new List<CarCost>(); 
 
    XmlDocument xmlDocument = new XmlDocument(); 
    xmlDocumentLoad("testxml"); 
 
    XmlNodeList xmlNodeList = xmlDocumentSelectSingleNode("Car")ChildNodes; 
    foreach (XmlNode list in xmlNodeList) 
    { 
      CarCost carcost = new CarCost 
      ( 
        listSelectSingleNode("ID")InnerText, 
        listSelectSingleNode("uptime")InnerText, 
        listSelectSingleNode("downtime")InnerText, 
        floatParse(listSelectSingleNode("price")InnerText) 
      ); 
      resultListAdd(carcost); 
    } 
 
    IEnumerator enumerator = resultListGetEnumerator(); 
    while (enumeratorMoveNext()) 
    { 
      CarCost carCost = enumeratorCurrent as CarCost; 
      ConsoleWriteLine(carCostID + " " + carCostUpTime + " " + carCostDownTime + " " + carCostPrice); 
    } 
  } 
} 
 
public class CarCost 
{ 
  public CarCost(string id, string uptime, string downtime, float price) 
  { 
    thisID = id; 
    thisUpTime = uptime; 
    thisDownTime = downtime; 
    thisPrice = price; 
  } 
  public string ID { get; set; } 
  public string UpTime { get; set; } 
  public string DownTime { get; set; } 
  public float Price { get; set; } 
}