如何从 XmlDocument 中的多个元素创建业务对象的集合

发布于 2024-10-05 20:44:07 字数 1638 浏览 3 评论 0原文

我正在尝试使用 .net 4.0/c# 从以下 xml 文档创建业务对象的集合,

    <WebServices ErrorFound="False" ServerDateTime="30/11/2010 14:58:58">
        <Results>
            <Users TotalResults="5">
                <UserName UserID="2">John</UserName>
                <UserName UserID="3">Dave</UserName>
                <UserName UserID="4">Jim</UserName>
                <UserName UserID="5">Bob</UserName>
            </Users>
        </Results>
    </WebServices>

这是我需要创建的类,

    public class User
    {
        public string Name { get; set; }
        public int ID { get; set; }
    }

每个 Users 子元素都应该是该类的一个新实例。 到目前为止,我有这个接受 XmlDocument 的方法。

public static IEnumerable<User> GetUser(XmlDocument xmlDoc)
{
    XmlReader reader = XmlReader.Create(new StringReader(xmlDoc.OuterXml));
    XDocument doc = XDocument.Load(reader);

    var user = from u in doc.Descendants("WebServices").DescendantsAndSelf("Users")
               select new User()
               {
                   Name = u.Element("UserName").Value,
                   ID = int.Parse(u.Element("UserName").Attribute("UserID").Value)
               };

     List<User> userInstance = user.ToList();
     IEnumerable<User> users= from u in userInstance
                              select u;
     return users;

 }

就从第一个子元素生成对象的一个​​实例而言,这工作得很好,但我不确定如何从所有元素创建多个实例。 我需要能够返回 User 对象的集合,例如 Collection; users = new Collection()

我可能完全找错了树。非常感谢任何帮助。

I'm trying to create a collection of business objects from the following xml document using .net 4.0/c#

    <WebServices ErrorFound="False" ServerDateTime="30/11/2010 14:58:58">
        <Results>
            <Users TotalResults="5">
                <UserName UserID="2">John</UserName>
                <UserName UserID="3">Dave</UserName>
                <UserName UserID="4">Jim</UserName>
                <UserName UserID="5">Bob</UserName>
            </Users>
        </Results>
    </WebServices>

This is the class I need to create

    public class User
    {
        public string Name { get; set; }
        public int ID { get; set; }
    }

Each of the Users child elements should be a new instance of the class.
So far I have this method which accepts an XmlDocument.

public static IEnumerable<User> GetUser(XmlDocument xmlDoc)
{
    XmlReader reader = XmlReader.Create(new StringReader(xmlDoc.OuterXml));
    XDocument doc = XDocument.Load(reader);

    var user = from u in doc.Descendants("WebServices").DescendantsAndSelf("Users")
               select new User()
               {
                   Name = u.Element("UserName").Value,
                   ID = int.Parse(u.Element("UserName").Attribute("UserID").Value)
               };

     List<User> userInstance = user.ToList();
     IEnumerable<User> users= from u in userInstance
                              select u;
     return users;

 }

This works fine as far as producing one instance of the object from the first child element is concerned but I am unsure as to how to create multiple instances from all the elements.
I need to be able to return a collection of the User objects eg Collection<User> users = new Collection<User>()

I could be barking up completely the wrong tree. Any help is much appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

面犯桃花 2024-10-12 20:44:07

使用 XPath 您可以编写如下代码:

public class User
{
    public string Name { get; set; }
    public int ID { get; set; }
} 

static void Main(string[] args)
{
    string xml =
        "<WebServices ErrorFound='False' ServerDateTime='30/11/2010 14:58:58'>" +
            "<Results>" +
                "<Users TotalResults='5'>" +
                    "<UserName UserID='2'>John</UserName>" +
                    "<UserName UserID='3'>Dave</UserName>" +
                    "<UserName UserID='4'>Jim</UserName>" +
                    "<UserName UserID='5'>Bob</UserName>" +
                    "</Users>" +
            "</Results>" +
        "</WebServices>";

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);

    var users = from userNameElement in doc.SelectNodes("/WebServices/Results/Users/UserName").OfType<XmlElement>()
                select new User
                {
                    Name = userNameElement.InnerText,
                    ID = Int32.Parse(userNameElement.GetAttribute("UserID"))
                };

    foreach (var user in users)
    {
        Console.WriteLine(user.ID.ToString() + ": " + user.Name);
    }
}

Using XPath you can write the code like this:

public class User
{
    public string Name { get; set; }
    public int ID { get; set; }
} 

static void Main(string[] args)
{
    string xml =
        "<WebServices ErrorFound='False' ServerDateTime='30/11/2010 14:58:58'>" +
            "<Results>" +
                "<Users TotalResults='5'>" +
                    "<UserName UserID='2'>John</UserName>" +
                    "<UserName UserID='3'>Dave</UserName>" +
                    "<UserName UserID='4'>Jim</UserName>" +
                    "<UserName UserID='5'>Bob</UserName>" +
                    "</Users>" +
            "</Results>" +
        "</WebServices>";

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);

    var users = from userNameElement in doc.SelectNodes("/WebServices/Results/Users/UserName").OfType<XmlElement>()
                select new User
                {
                    Name = userNameElement.InnerText,
                    ID = Int32.Parse(userNameElement.GetAttribute("UserID"))
                };

    foreach (var user in users)
    {
        Console.WriteLine(user.ID.ToString() + ": " + user.Name);
    }
}
捎一片雪花 2024-10-12 20:44:07

好吧,我终于弄清楚我的代码出了什么问题。
现在我不再

var user = from u in doc.Descendants("WebServices").DescendantsAndSelf("Users")
        select new User()
        {
            Name = u.Element("UserName").Value,
            ID = int.Parse(u.Element("UserName").Attribute("UserID").Value)
        };

var user = (from u in doc.Descendants("UserName")
        select new Provider()
        {
            Name = u.Value,
            ID = int.Parse(u.Attribute("UserID").Value)
        });

这样的语句: doc.Descendants("UserName") 基本上生成一个可以迭代的 UserName 元素数组,然后我可以直接访问该元素的值并设置它到我的班级属性。

Ok, so I finally figured out what was wrong with my code.
Instead of

var user = from u in doc.Descendants("WebServices").DescendantsAndSelf("Users")
        select new User()
        {
            Name = u.Element("UserName").Value,
            ID = int.Parse(u.Element("UserName").Attribute("UserID").Value)
        };

I now have

var user = (from u in doc.Descendants("UserName")
        select new Provider()
        {
            Name = u.Value,
            ID = int.Parse(u.Attribute("UserID").Value)
        });

the statement: doc.Descendants("UserName") basically produces an array of the UserName elements which can be iterated through, I can then directly access the value of that element and set it to my class properties.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文