簡體   English   中英

如何解析這個Xml類型的字符串

[英]how to parse this Xml type string

有人可以指導我如何解析此Xml類型的字符串嗎?

<data>
  <LastUpdate></LastUpdate>
  <AC1>12</AC1>
  <AC2>13</AC2>
  <AC3>14</AC3>
  <Moter></Moter>
  <Fan1></Fan1>
  <Fan2></Fan2>
  <TubeLight1></TubeLight1>
  <TubeLight2></TubeLight2>
  <Moter></Moter>
  <CloseAll></CloseAll>
</data>

我需要在String或List或Dictionary中獲得所有結果,例如AC1 = 12,AC2 = 13等等

提前致謝

使用XDocument.Parse方法:

string data = @"<data>
                  <LastUpdate></LastUpdate>
                  <AC1>12</AC1>
                  <AC2>13</AC2>
                  <AC3>14</AC3>
                  <Moter></Moter>
                  <Fan1></Fan1>
                  <Fan2></Fan2>
                  <TubeLight1></TubeLight1>
                  <TubeLight2></TubeLight2>
                  <Moter></Moter>
                  <CloseAll></CloseAll>
            </data>";

XDocument xmlDoc = XDocument.Parse(data);

var parsedData = from obj in xmlDoc.Descendants("data")
                 select new
                 {
                     LastUpdate = obj.Element("LastUpdate").Value,
                     AC1 = obj.Element("AC1").Value,
                     AC2 = obj.Element("AC1").Value,
                     ... and so on
                 }

祝好運!

如果要將xml數據字符串解析為'Dataset'則可以使用此示例

    string xmlString = @"/*.. .. .*/";

    DataSet data = new DataSet();

    data.ReadXml(new StringReader(xmlString));

這應該可以,但是您必須從XML中刪除重復的Moter元素-只有這樣才能使用字典:

XDocument doc = XDocument.Load("test.xml");
var dictionary = doc.Descendants("data")
                    .Elements()
                    .ToDictionary(x => x.Name.ToString(), x => x.Value);
string ac1Value = dictionary["AC1"];

如果您想使用Linq to XML,那么它將類似於:

        XElement root = XElement.Parse(s);
        Dictionary<XName, string> dict = root
            .Elements()
            .Select(x => new {key = x.Name, value = x.Value})
            .ToDictionary(x => x.key, x => x.value);

只要確保您以所需的方式處理重復項即可。

我更喜歡使用XLinq。 這是示例(在VB.NET中):

 Private Sub ParseIt()

        Dim xml = XElement.Parse(sampleXml)

        Dim dic As New Dictionary(Of String, String)

        For Each item In xml.Elements
            dic.Add(item.Name.LocalName, item.Value)
        Next

    End Sub

您也可以像這樣使用它(我更喜歡這種方法):

Private Sub ParseIt()

    Dim xml = XElement.Parse("")

    Dim dic = (From item In xml.Elements).ToDictionary(Function(obj) obj.Name.LocalName, Function(obj) obj.Value)

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM