如何将XML解析为IList<;BusinessObject>;在C#中使用XPath

本文关键字:BusinessObject gt XPath lt XML IList | 更新日期: 2023-09-27 18:01:09

我在字符串中有以下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?

我需要学习这个进行训练。

谢谢你的回答。

如何将XML解析为IList<;BusinessObject>;在C#中使用XPath

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+

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

也许这对你有更多帮助:

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

谨致问候,尼科

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)

请看下面的链接,例如关于Linq到XML的链接。