如何在C#中使用XPath将XML解析为IList <businessobject>?</businessobject>

时间:2011-07-04 11:19:26

标签: c# .net xml xpath

我在字符串中有以下XML:

<RootElement>
    <Data>
        <Row>
            <Id>1</Id>
            <Name>Foo</Name>
        </Row>
        <Row>
            <Id>2</Id>
            <Name>Bar</Name>
        </Row>
    </Data>
</RootElement>

以下课程:

public class BusinessObject
{
    public int Id { get; set; }
    public string Name { get; set; }
}

如何使用XPath将Row元素中的所有数据解析为IList?

我需要学习这项培训。

感谢您的回答。

3 个答案:

答案 0 :(得分:4)

IEnumerable<BusinessObject> ParseWithXPath(string xml)
{
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    foreach (XmlNode node in doc.DocumentElement.SelectNodes("Data/Row")) // XPath query
    {
        yield return new BusinessObject
        {
            Id = Int32.Parse(node.SelectSingleNode("Id").InnerText),
            Name = node.SelectSingleNode("Name").InnerText
        };
    }
}

用法:

IEnumerable<BusinessObject> seq = ParseWithXPath(xml); // .NET 2.0+

IList<BusinessObject> list = new List<BusinessObject>(seq); // .NET 2.0+

答案 1 :(得分:3)

在我为你编写示例时,我发现你已经找到了一个相当干净的解决方案。

也许这会对你有所帮助:

internal static class XMLToListWithXPathExample
{
    static XmlDocument xmlDocument;
    static List<BusinessObject> listBusinessObjects;
    static string sXpathStatement = "/Data/Row";

    static void LoadXMLData(string p_sXMLDocumentPath)
    {   
        xmlDocument = new XmlDocument(); // setup the XmlDocument
        xmlDocument.Load(p_sXMLDocumentPath); // load the Xml data
    }

    static void XMLDocumentToList()
    {
        listBusinessObjects = new List<BusinessObject>(); // setup the list
        foreach (XmlNode xmlNode in xmlDocument.SelectNodes(sXpathStatement)) // loop through each node
        {
            listBusinessObjects.Add( // and add it to the list
                new BusinessObject(
                    int.Parse(xmlNode.SelectSingleNode("Id").InnerText), // select the Id node
                    xmlNode.SelectSingleNode("Name").InnerText)); // select the Name node
        }

    }
}

public class BusinessObject
{
    public int Id { get; set; }
    public string Name { get; set; }

    // constructor
    public BusinessObject(int p_iID, string p_sName)
    {
        Id = p_iID;
        Name = p_sName;
    }

}

此致 尼科

答案 2 :(得分:0)

IEnumerable<BusinessObject> busObjects = from item in doc.Descendants("Row")
                                         select new BusinessObject((int)item.Element("Id"), (string)item.Element("Name"));

您可以尝试类似上述内容。您的BusinessObject构造函数应该采用这两个参数。 BusinessObject(int id, string name)

请查看以下link,例如Linq to XML。