【问题标题】:Help Parsing a field using LINQ to XML帮助使用 LINQ to XML 解析字段
【发布时间】:2011-02-15 16:06:12
【问题描述】:

Xml格式如下

<ExtraFields>
        <Field id="Attribute 1" description="Attribute1">
          <Value>Value of Attribute 1</Value>
        <Field id="Attribute 2" description="Attribute2">
          <Value>Value of Attribute 2</Value>
        <Field id="Attribute 3" description="Attribute3">
          <Value>Value of Attribute 3</Value>  
</ExtraFields>

我正在编写一个应该返回以下值的 LINQ 语句

Value of Attribute 1
Value of Attribute 2
Value of Attribute 3

当父节点具有字段 id="Attribute X" description="AttributeX" 的属性时,它返回每个属性的值

【问题讨论】:

  • 你能发布一些示例 xml 吗?还问一个问题?
  • 嗨,Morpheus,我认为 XML 示例会有所帮助,并且可以稍微澄清一下您想要什么。你的问题有点不清楚(至少对我来说)。
  • 抱歉不清楚。到目前为止,在过去的一年里,我从来没有在这里发布任何东西。这是我第一次。下次我会坚持正确的标准!!感谢您的回复!

标签: c# linq


【解决方案1】:

试试这个

var  doc = XElement.Load("test.xml");
var results = doc.Descendants("Value").Where(x =>  
x.Parent.Attribute("id").Value.StartsWith("Attribute")).Select(x => x.Value);

【讨论】:

  • 我会试试这个。非常感谢!
【解决方案2】:

假设您的真正意思,您发布的是格式错误的 XML:

<ExtraFields>
  <Field id="Attribute 1" description="Attribute1">
    <Value>Value of Attribute 1</Value>
  </Field>
    <Field id="Attribute 2" description="Attribute2">
      <Value>Value of Attribute 2</Value>
    </Field>
    <Field id="Attribute 3" description="Attribute3">
        <Value>Value of Attribute 3</Value>
    </Field>
</ExtraFields>

在这种情况下,以下方法可以解决您使用 LINQ to XML 的问题:

XElement doc = XElement.Load("test.xml");
var results = doc.Descendants("Value")
                 .Where ( x=> x.Parent.Attribute("id").Value.StartsWith("Attribute")
                              && x.Parent.Attribute("description") != null
                              && x.Parent.Attribute("description").Value.StartsWith("Attribute"))
                 .Select( x => new { Id = x.Parent.Attribute("id").Value, 
                                     Value = x.Value });

foreach(var result in results)
{
    Console.WriteLine(string.Format("{0} : Value = {1}", 
                      result.Id, 
                      result.Value));
}

【讨论】:

  • 如果您检查x.Parent.Attribute("description") != null,您还应该检查x.Parent.Attribute("id") 和所有其他空检查。
  • 这可能是真的,我从 xml 的结构中假设 id 属性将始终存在 - 如果该假设无论如何都是错误的,则 id 也应该有一个空检查
猜你喜欢
  • 2012-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-21
  • 1970-01-01
相关资源
最近更新 更多