如何从没有标准格式的XML中检索值?

时间:2022-10-30 23:32:19

I can't seem to find an article with this same problem.

我似乎找不到一篇有同样问题的文章。

I have an XML file like this:

我有一个这样的XML文件:

<user id="" name="" termsofuse="http://boardgamegeek.com/xmlapi/termsofuse">
<firstname value="" /> 
<lastname value="" /> 
<avatarlink value="N/A" /> 
<yearregistered value="" /> 
<lastlogin value="2012-10-04" /> 
<stateorprovince value="" /> 
<country value="" /> 
<webaddress value="" /> 
<xboxaccount value="" /> 
<wiiaccount value="" /> 
<psnaccount value="" /> 
<battlenetaccount value="" /> 
<steamaccount value="" /> 
<traderating value="363" /> 
</user>

And I am using the following code to extract the data:

我使用以下代码提取数据:

static string QueryTheData(XDocument doc)
{
  var data = from item in doc.Descendants("user")
             select new
             {
               avatarlink = item.Element("avatarlink").Value,
               lastlogin = item.Element("lastlogin").Value,
             };
  var t = "";
  foreach (var p in data)
    t += p.ToString();
  return t;
}

But my values returned are null. I'm wondering if it's because the XML file begins:

但是返回的值是空的。我想知道是不是因为XML文件开始了:

<user id="" name="" termsofuse="http://boardgamegeek.com/xmlapi/termsofuse">

Whereas in all the examples I have found the XML begins like this:

而在所有示例中,我发现XML的开头是这样的:

<user> ... etc

How can I read these values in this format?

如何以这种格式读取这些值?

2 个解决方案

#1


3  

You want to get the value of attribute value. Try this

您需要获取属性值的值。试试这个

avatarlink = item.Element("avatarlink").Attribute("value").Value

But I would go this way

但是我要走这条路

var list = doc.Descendants("user")
        .Select(u=>u.Elements().ToDictionary(e=>e.Name.LocalName,e=>e.Attribute("value").Value))
        .ToList();

where every item of the final list contains a dictionary of elements and their values

最终列表中的每一项都包含元素及其值的字典

var lastlogin = list[0]["lastlogin"];

#2


2  

The Value attribute is reading the value of the node, you are probably looking for something like:

Value属性正在读取节点的值,您可能正在查找以下内容:

(string)item.Element("avatarlink").Attribute("value")

#1


3  

You want to get the value of attribute value. Try this

您需要获取属性值的值。试试这个

avatarlink = item.Element("avatarlink").Attribute("value").Value

But I would go this way

但是我要走这条路

var list = doc.Descendants("user")
        .Select(u=>u.Elements().ToDictionary(e=>e.Name.LocalName,e=>e.Attribute("value").Value))
        .ToList();

where every item of the final list contains a dictionary of elements and their values

最终列表中的每一项都包含元素及其值的字典

var lastlogin = list[0]["lastlogin"];

#2


2  

The Value attribute is reading the value of the node, you are probably looking for something like:

Value属性正在读取节点的值,您可能正在查找以下内容:

(string)item.Element("avatarlink").Attribute("value")