C#Xml字符串分解帮助 [英] C# Xml string breakup help

查看:84
本文介绍了C#Xml字符串分解帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

希望有人能帮忙.我是xml的新手,需要一些帮助来从XMLNodes获取信息.这是字符串的示例:

Hi guys

Hope someone can help. I am new to xml and need some help getting information from the XMLNodes. Here is an example of the string:

<livepackage><status><statustime>1335041400489</statustime><statusitem id=\"1\" value=\"1\" /><statusitem id=\"2\" value=\"0\" /><statusitem id=\"3\" value=\"0\" /><statusitem id=\"5\" value=\"1\" /></status></livepackage>\r\n\r\n




我需要获取每个状态项ID 1到7的值.

因此,如果我想要statusitem id = 1,我将得到1.


任何帮助将不胜感激.

在此先感谢




I need to get the value of each statusitem id 1 to 7.

So if I want statusitem id=1 I will get 1.


Any help will be appreciated.

Thanks in advance

推荐答案

以下代码可用于使用LINQ to XML
检索值.
The following code can be used to retrieve the value using LINQ to XML

string xmlString = @"<?xml version=""1.0""?><livepackage><status><statustime>1335041400489</statustime><statusitem id=""1"" value=""1"" /><statusitem id=""2"" value=""0"" /><statusitem id=""3"" value=""0"" /><statusitem id=""5"" value=""1.5"" /></status></livepackage>";

XDocument xDocument1 = XDocument.Parse(xmlString, LoadOptions.None);
string searchId="1";

string attributeValue = (from xElement in xDocument1.Descendants("statusitem")
          where string.Equals(xElement.Attribute("id").Value,searchId, StringComparison.InvariantCulture)
          select xElement.Attribute("value").Value).FirstOrDefault ();
Console.WriteLine (attributeValue);



以下代码可用于使用xmlDocument class
检索值



And the following code can be used to retrieve the value useing xmlDocument class

string xmlString = @"<?xml version=""1.0""?><livepackage><status><statustime>1335041400489</statustime><statusitem id=""1"" value=""1"" /><statusitem id=""2"" value=""0"" /><statusitem id=""3"" value=""0"" /><statusitem id=""5"" value=""1.5"" /></status></livepackage>";

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString);
var nodes = xmlDoc.GetElementsByTagName("statusitem");
string searchId= "1";

foreach (XmlNode element in nodes)
{
    if (string.Equals(element.Attributes["id"].Value,searchId, StringComparison.InvariantCulture)){
        Console.WriteLine (element.Attributes["value"].Value);
        break;
    }
}


我认为这可能对您有所帮助.


I think it may be helpful to you.


您可以尝试一下
You could try this
// Create DataTable
var table = new DataTable();			
table.ReadXml("Yourfile.xml");


然后检查表的内容


then examine the contents of the table


这篇关于C#Xml字符串分解帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆