[英]how to parse this Xml type string
Can some one guide me 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>
I need to get all result in String or List or dictionary like AC1=12 , AC2=13 and so on 我需要在String或List或Dictionary中获得所有结果,例如AC1 = 12,AC2 = 13等等
Thnaks in advance 提前致谢
Use XDocument.Parse method: 使用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
}
Good luck! 祝好运!
If you want to parse xml data string into 'Dataset'
then you can use this sample 如果要将xml数据字符串解析为
'Dataset'
则可以使用此示例
string xmlString = @"/*.. .. .*/";
DataSet data = new DataSet();
data.ReadXml(new StringReader(xmlString));
This should work but you have to remove the duplicate Moter
element from your XML - only then you can use a dictionary: 这应该可以,但是您必须从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"];
If you wanted to go for Linq to XML then it would look something like: 如果您想使用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);
Just make sure you deal with duplicates the way you want. 只要确保您以所需的方式处理重复项即可。
I prefer using XLinq. 我更喜欢使用XLinq。 Here is the sample (in VB.NET):
这是示例(在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.