开发者

Help Parsing a field using LINQ to XML

The Xml is formatted as follows

<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">开发者_C百科;
          <Value>Value of Attribute 3</Value>  
</ExtraFields>

I am writing a LINQ statement which should return the following values

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

it returns me the value of each attribute when the parent node has an attribute of Field id="Attribute X" description="AttributeX"


try this

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


What you posted is malformed XML, assuming your really mean:

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

In that case the following solves your problem with 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));
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜