繁体   English   中英

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

[英]How to parse XML to an IList<BusinessObject> using XPath in C#?

我在字符串中有以下 XML :

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

以及以下 class:

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

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

我需要学习这个以进行培训。

感谢您的回答。

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM