开发者

how to parse this Xml type string

Can some one guide me how to parse this Xml type string开发者_如何学运维 ?

<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>

I need to get all result in String or List or dictionary like AC1=12 , AC2=13 and so on

Thnaks in advance


Use XDocument.Parse method:

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
                 }

Good luck!


This should work but you have to remove the duplicate Moter element from your XML - only then you can use a dictionary:

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


If you wanted to go for Linq to XML then it would look something like:

        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);

Just make sure you deal with duplicates the way you want.


I prefer using XLinq. Here is the sample (in 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

Also you can use it like this (I prefer this method):

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


If you want to parse xml data string into 'Dataset' then you can use this sample

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

    DataSet data = new DataSet();

    data.ReadXml(new StringReader(xmlString));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜