如何通过父节点值读取父级的XML并使用属性分配给类。 [英] How to read XML with parent by parent node values and assign to class with property.

查看:98
本文介绍了如何通过父节点值读取父级的XML并使用属性分配给类。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像下面这样的xml



i have an xml like below

<Parents>
<parent>
<child1>001</Child1>
<child2>Name1</Child2>
<child3>Address1</Child3>
<child4>Address2</Child4>
</parent>
<parent>
<child1>002</Child1>
<child2>Name2</Child2>
<child3>Address1</Child3>
<child4>Address2</Child4>
</parent>
<parent>
<child1>003</Child1>
<child2>Name3</Child2>
<child3>Address1</Child3>
<child4>Address2</Child4>
</parent>
<parent>
<child1>004</Child1>
<child2>Name4</Child2>
<child3>Address1</Child3>
<child4>Address2</Child4>
</parent>
</Parents>





并且有一个C#课程如下





and have a class in C# as below

public class xmldata
{
private string child1{get;set;}
private string child2{get;set;}
private string child3{get;set;}
private string child4{get;set;}
}





i想要阅读并将所有xml elemet值分配给下面的类列表





i want to read and assign all the xml elemet values to list of class like below

List<xmldata> data1 = new List<xmldata>();





此列表应包含所有四个父元素值。



我尝试了什么:



i试图通过Xdocument(LinQ)读取xml错误并且无法实现它。



this list should have all the four parent element values.

What I have tried:

i have tried to read the xml with Xdocument (LinQ) getting error and unable to achieve it.

推荐答案

您可以在Visual Studio 2017中使用此技巧:



转到编辑菜单

选择粘贴特殊

选择将XML粘贴为类



确保所有内容具有相同的大小写,文件名为 MyChildren.xml

You can use this trick in Visual Studio 2017:

Goto Edit menu
Select 'Paste special'
Select 'Paste XML as classes'

Make sure everything has the same case, file name 'MyChildren.xml':
<parent>
<child1>001</child1>
<child2>name1</child2>
<child3>address1</child3>
<child4>address2</child4>
</parent>
<parent>
<child1>002</child1>
<child2>name2</child2>
<child3>address1</child3>
<child4>address2</child4>
</parent>
<parent>
<child1>003</child1>
<child2>name3</child2>
<child3>address1</child3>
<child4>address2</child4>
</parent>
<parent>
<child1>004</child1>
<child2>name4</child2>
<child3>address1</child3>
<child4>address2</child4>
</parent>





示例用法表格:



Example usage Form:

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Drawing;
    using System.IO;
    using System.Text;
    using System.Windows.Forms;
    using System.Xml;
    using System.Xml.Serialization;

    public partial class Form1 : Form
    {
        /// <summary>
        /// The config for XML serialization.
        /// </summary>
        private Children childrenXml;

        public Form1()
        {
            this.InitializeComponent();
			this.SettingsRead("MyChildren.xml")
		}

        private bool SettingsRead(string fileNameFull)
        {
            bool result = false;

            try
            {
                var serializer = new XmlSerializer(this.childrenXml.GetType());
                string str = File.ReadAllText(fileNameFull);

                using (TextReader reader = new StringReader(str))
                {
                    this.childrenXml = (Children)serializer.Deserialize(reader);
                }

                result = true;
            }
            catch (Exception ex)
            {
                Debug.Print("SettingsRead() " + ex.Message);
            }

            return result;
        }
}



类文件:


Class file:

namespace MyChildren
{
    using System.Collections.Generic;

    public class Children
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Children"/> class.
        /// </summary>
        public Children()
        {
            this.ChildrenItemList = new List<ChildrenItem>();
        }
		
		/// <summary>
        /// Gets or sets the ChildrenItemList
        /// </summary>
        public List<ChildrenItem> ChildrenItemList { get; set; }
    }

    /// <summary>
    /// ChildrenItem subclass defines one element in the Children.
    /// </summary>
    public class ChildrenItem
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ChildrenItem"/> class.
        /// </summary>
        public ChildrenItem()
        {
            // Only needed for serializer.
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ChildrenItem"/> class.
        /// </summary>
        public ChildrenItem(string c1, string c2, string c3, string c4)
        {
            this.Child1 = c1;
            this.Child2 = c2;
            this.Child3 = c3;
            this.Child4 = c4;
        }

        /// <summary>
        /// Gets or sets the Child(s)
        /// </summary>
        public string Child1 { get; set; }
		
		public string Child2 { get; set; }

		public string Child3 { get; set; }

		public string Child4 { get; set; }
	}
}


Google this: c#deserialize nested xml
Google this: c# deserialize nested xml


我建议您下载Nuget包ExtendedXmlSerializer。实例化列表< XmlData> 并使用Serializer对其进行序列化,然后检查输出。

What I suggest you do is to download the Nuget package ExtendedXmlSerializer. Instantiate a List<XmlData> and Serialize it using the Serializer, then examine the output.

List<XmlData> parents = new List<XmlData>
{
    new XmlData{child1="A1",child2="A2",child3="A3"},
    new XmlData{child1="B1",child2="B2",child3="B3"},
    new XmlData{child1="C1",child2="C2",child3="C3"}
};
   IExtendedXmlSerializer serializer = new ConfigurationContainer().Create();
   var xml = serializer.Serialize(parents);



输出Xml将类似于这个。


The output Xml will be similar to this.

<?xml version="1.0" encoding="utf-8"?><List xmlns:ns1="clr-namespace:XmlTest;
assembly=XmlTest" xmlns:exs="https://extendedxmlserializer.github.io/v2" exs:arguments="ns1:XmlData" xmlns="https://extendedxmlserializer.github.io/system">
<Capacity>4</Capacity>
<ns1:XmlData>
<child1>A1</child1>
<child2>A2</child2>
<child3>A3</child3>
</ns1:XmlData>
<ns1:XmlData>
<child1>B1</child1>
<child2>B2</child2>
<child3>B3</child3>
</ns1:XmlData>
<ns1:XmlData>
<child1>C1</child1>
<child2>C2</child2>
<child3>C3</child3>
</ns1:XmlData></List>



接下来,您要重新构建xml数据,使其处于相同的格式。可以省略 Capacity 元素。如果您修复的数据文件格式是固定的,您可以通过将其加载到 StringBuilder 并使用附加进行重组。和替换方法以根据需要添加和替换元素名称。


Next you want to restructure your xml data so that it's in the same format. The Capacity element can be omitted. If the data file format you have is fixed, you can restructure it by loading it into a StringBuilder and employing the Append and Replace methods to add and replace element names as required.

string xmlContent = File.ReadAllText(@"C:\Temp\orig.xml");
StringBuilder sb = new StringBuilder(xmlContent).
Replace("<Parents>",xmlHeading).Replace("</Parents>","").
Replace("parent","ns1:XmlData").Append("/List>");
IExtendedXmlSerializer serializer = new ConfigurationContainer().Create();
string data = sb.ToString();
var MyXmlDataList = serializer.Deserialize<List<XmlData>>(data);


这篇关于如何通过父节点值读取父级的XML并使用属性分配给类。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆