LINQ to XML查询和将XML文档转换为XDocument的扩展方法

时间:2011-06-22 20:36:09

标签: linq-to-xml

这是传递给CreateListOfAddresses()方法的XML文档:

<?xml version="1.0"?>
    <AddressValidateResponse>
        <Address ID="0">
        <Address2>8 WILDWOOD DR</Address2>
        <City>OLD LYME</City>
        <State>CT</State>
        <Zip5>06371</Zip5>
        <Zip4>1844</Zip4>
    </Address>
</AddressValidateResponse>

这是我的方法:

    private List<AddressBlockResponse> CreateListOfAddresses(XmlDocument xmlDoc)
    {
        // Convert XML document to xdocument so we can use LINQ.
        XDocument xDoc = xmlDoc.ToXDocument();

        var address = from a in xDoc.Descendants("AddressValidateResponse")
                      select new AddressBlockResponse
                      {
                          Order = int.Parse(a.Attribute("ID").Value),
                          AddressLine2 = a.Element("Address2").Value,
                          City = a.Element("City").Value,
                          State = a.Element("State").Value,
                          ZipCode = a.Element("Zip5").Value,
                          ZipPlus4 = a.Element("Zip4").Value
                      };
        return address.ToList();
    }

以下是将我的XML文档转换为XDocument类型的扩展方法:

public static XDocument ToXDocument(this XmlDocument xmlDocument)
{
    using (var nodeReader = new XmlNodeReader(xmlDocument))
    {
        nodeReader.MoveToContent();
        return XDocument.Load(nodeReader);
    }
}

这是我的目标:

[Serializable]
public struct AddressBlockResponse
{
    // Standardized address returned from the service
    [DataMember(IsRequired = true)]
    public int Order;

    [DataMember(IsRequired = true)]
    public string AddressLine1;

    [DataMember(IsRequired = false)]
    public string AddressLine2;

    [DataMember(IsRequired = true)]
    public string City;

    [DataMember(IsRequired = true)]
    public string State;

    [DataMember(IsRequired = true)]
    public string ZipCode;

    [DataMember(IsRequired = true)]
    public string ZipPlus4;
}

这是我的问题:CreateListOfAddresses()方法返回

  

枚举没有产生结果

我做错了什么?

1 个答案:

答案 0 :(得分:0)

看起来您的问题是AddressValidateResponse是您文档的根节点。

您应将其更改为:

var address = from a in xDoc.Descendants("Address")
                  select new AddressBlockResponse
                  {
                      // stuff
                  };

当你使用像

这样的xelements时
City = a.Element("City").Value,

你应该这样做:

City = (string)a.Element("City"),

因为如果元素不存在,程序将抛出空引用异常。我知道你可能总是有这些xml节点,但我认为这只是一个好习惯。