为最简单的 xml 文件编写最简单的 XML 反序列化类。如何避免嵌套?在根目录反序列化?

发布于 2024-09-01 19:23:57 字数 1724 浏览 6 评论 0原文

我想反序列化一个 xml 文件,该文件必须采用这种形式

<Basket>
  <Fruit>Apple</Fruit>
  <Fruit>Orange</Fruit>
  <Fruit>Grapes</Fruit>
</Basket>

。在我在互联网上阅读的示例中,我能找到的最不可能的格式如下,

<Basket>
  <FruitArray>
    <Fruit>Apple</Fruit>
  </FruitArray>
  <FruitArray>
    <Fruit>Orange</Fruit>
  </FruitArray>
  <FruitArray>
    <Fruit>Grapes</Fruit>
  </FruitArray>
</Basket>

并且具有以下反序列化类,用于将其转换为类对象。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace XMLSerialization_Basket
{
    [System.Xml.Serialization.XmlRootAttribute("Basket", Namespace = "BasketNamespace", IsNullable = false)]
    public class Basket
    {
        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("FruitArray")]
        public FruitArray[] objFruitArray;
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTypeAttribute(Namespace = "BasketNamespace")]
    public class FruitArray
    {

        /// <remarks/>
        private string _Fruit;

        public string Fruit
        {

            get { return _Fruit; }
            set { _Fruit = value; }
        }
    }


}

我可以直接在顶级类下添加类似以下内容

    private string _Fruit;

    public string Fruit
    {

        get { return _Fruit; }
        set { _Fruit = value; }
    }

并避免数组嵌套吗?

我的目标是反序列化以下格式的 xml

<Basket>
  <Fruit>Apple</Fruit>
  <Fruit>Orange</Fruit>
  <Fruit>Grapes</Fruit>
</Basket>

I want to deserialize an xml file which has to be just in this form

<Basket>
  <Fruit>Apple</Fruit>
  <Fruit>Orange</Fruit>
  <Fruit>Grapes</Fruit>
</Basket>

Out of the examples I read on internet the least possible format I could find was the following

<Basket>
  <FruitArray>
    <Fruit>Apple</Fruit>
  </FruitArray>
  <FruitArray>
    <Fruit>Orange</Fruit>
  </FruitArray>
  <FruitArray>
    <Fruit>Grapes</Fruit>
  </FruitArray>
</Basket>

and that has the following deserialization class for converting it into a class object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace XMLSerialization_Basket
{
    [System.Xml.Serialization.XmlRootAttribute("Basket", Namespace = "BasketNamespace", IsNullable = false)]
    public class Basket
    {
        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("FruitArray")]
        public FruitArray[] objFruitArray;
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTypeAttribute(Namespace = "BasketNamespace")]
    public class FruitArray
    {

        /// <remarks/>
        private string _Fruit;

        public string Fruit
        {

            get { return _Fruit; }
            set { _Fruit = value; }
        }
    }


}

Can I add something like the following directly under top class

    private string _Fruit;

    public string Fruit
    {

        get { return _Fruit; }
        set { _Fruit = value; }
    }

and avoid the array nesting?

my goal is to deserialize an xml of following format

<Basket>
  <Fruit>Apple</Fruit>
  <Fruit>Orange</Fruit>
  <Fruit>Grapes</Fruit>
</Basket>

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

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

发布评论

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

评论(5

怂人 2024-09-08 19:23:57

恕我直言,我会修改我的 XML 和对象以反序列化为以下内容。

这是 C#(应该编译;))

 using System.Xml.Serialization;
    using System.Xml.Schema;
    [XmlRootAttribute(Namespace = "", IsNullable = false)]
    public class Basket
    {
        [XmlArrayAttribute("Fruits", Form = XmlSchemaForm.Unqualified)]
        [XmlArrayItemAttribute("Fruit", typeof(string), Form = XmlSchemaForm.Unqualified)]
        public List<string> _items;
    }

这是 XML

<Basket> 
  <Fruits> 
    <Fruit>Apple</Fruit> 
    <Fruit>Orange</Fruit> 
    <Fruit>Grapes</Fruit> 
  </Fruits> 
</Basket> 

With all respect I would modify my XML and object to deserialize into to the following.

Here is the C# (Should compile ;))

 using System.Xml.Serialization;
    using System.Xml.Schema;
    [XmlRootAttribute(Namespace = "", IsNullable = false)]
    public class Basket
    {
        [XmlArrayAttribute("Fruits", Form = XmlSchemaForm.Unqualified)]
        [XmlArrayItemAttribute("Fruit", typeof(string), Form = XmlSchemaForm.Unqualified)]
        public List<string> _items;
    }

Here is the XML

<Basket> 
  <Fruits> 
    <Fruit>Apple</Fruit> 
    <Fruit>Orange</Fruit> 
    <Fruit>Grapes</Fruit> 
  </Fruits> 
</Basket> 
猫烠⑼条掵仅有一顆心 2024-09-08 19:23:57

你应该只需要:

public class Basket {
    private List<string> fruits = new List<string>();
    [XmlElement("Fruit")]
    public List<string> Fruits {get {return fruits;}}
}

You should just need:

public class Basket {
    private List<string> fruits = new List<string>();
    [XmlElement("Fruit")]
    public List<string> Fruits {get {return fruits;}}
}
故笙诉离歌 2024-09-08 19:23:57
[XmlRoot("Basket")]
class Basket : List<Fruit>
{

}

[XmlRoot("Fruit")]
class Fruit
{
    [XmlText]
    string Value { get; set; }
}

或者使用 LINQ to XML:

public void Serialize(Basket b)
{
    XElement _root = new XElement("Basket", 
        b.Select(
            f => new XElement("Fruit", 
                new XText(f.Value))));

    _root.Save("file.xml");
}

public void Deserialize()
{
    Basket b = new Basket();

    XElement _root = XElement.Load("file.xml");
    foreach(XElement fruit in _root.Descendants("Fruit"))
    {
        Fruit f = new Fruit();
        f.Value = fruit.Value;
        basket.Add(f);
    }
}
[XmlRoot("Basket")]
class Basket : List<Fruit>
{

}

[XmlRoot("Fruit")]
class Fruit
{
    [XmlText]
    string Value { get; set; }
}

Or using LINQ to XML:

public void Serialize(Basket b)
{
    XElement _root = new XElement("Basket", 
        b.Select(
            f => new XElement("Fruit", 
                new XText(f.Value))));

    _root.Save("file.xml");
}

public void Deserialize()
{
    Basket b = new Basket();

    XElement _root = XElement.Load("file.xml");
    foreach(XElement fruit in _root.Descendants("Fruit"))
    {
        Fruit f = new Fruit();
        f.Value = fruit.Value;
        basket.Add(f);
    }
}
瀟灑尐姊 2024-09-08 19:23:57

上一篇文章绝对有效...

public class Basket { 
    private List<string> fruits = new List<string>(); 
    [XmlElement("Fruit")] 
    public List<string> Fruits {get {return fruits;}} 
} 

我组装了以下测试设备,它能够毫无问题地读取所述 XML。

var doc = new XmlDocument();
doc.Load("TheFile.xml");

var basket = XmlDeserialize<Basket>(doc.OuterXml);

public static T XmlDeserialize<T>(string serializedContent)
{
    T returnValue;

    if (String.IsNullOrEmpty(serializedContent))
    {
        returnValue = default(T);
    }
    else
    {
        var deSerializer = new XmlSerializer(typeof(T));
        var stringReader = new StringReader(serializedContent);

        try
        {
            returnValue = (T)deSerializer.Deserialize(stringReader);
        }
        catch (InvalidOperationException)
        {
            returnValue = default(T);
        }
    }

    return returnValue;
}

The previous post absolutely worked...

public class Basket { 
    private List<string> fruits = new List<string>(); 
    [XmlElement("Fruit")] 
    public List<string> Fruits {get {return fruits;}} 
} 

I put together the following test rig and it was able to read the stated XML with no problem.

var doc = new XmlDocument();
doc.Load("TheFile.xml");

var basket = XmlDeserialize<Basket>(doc.OuterXml);

public static T XmlDeserialize<T>(string serializedContent)
{
    T returnValue;

    if (String.IsNullOrEmpty(serializedContent))
    {
        returnValue = default(T);
    }
    else
    {
        var deSerializer = new XmlSerializer(typeof(T));
        var stringReader = new StringReader(serializedContent);

        try
        {
            returnValue = (T)deSerializer.Deserialize(stringReader);
        }
        catch (InvalidOperationException)
        {
            returnValue = default(T);
        }
    }

    return returnValue;
}
挽梦忆笙歌 2024-09-08 19:23:57

xml 架构应如下所示:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Basket">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="Fruit" type="xs:string" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

如果您保存 xsd(我们将其称为 example.xsd)并使用以下参数运行 xsd:

xsd.exe /c /n:BasketOfFruits sample.xsd

您将拥有此类:

namespace BasketOfFruits {
    using System.Xml.Serialization;


    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
    public partial class Basket {

        private string[] fruitField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("Fruit")]
        public string[] Fruit {
            get {
                return this.fruitField;
            }
            set {
                this.fruitField = value;
            }
        }
    }
}

这是一个要演示的示例程序:

using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using BasketOfFruits;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Basket myBasket = new Basket();
            myBasket.Fruit = new string[] { "Apple", "Orange", "Grapes" };

            XmlSerializer xs = new XmlSerializer(typeof(Basket));            
            XmlSerializerNamespaces emptyNamespace = new XmlSerializerNamespaces();
            emptyNamespace.Add(String.Empty, String.Empty);

            StringBuilder output = new StringBuilder();

            XmlWriter writer = XmlWriter.Create(output, 
                new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true });
            xs.Serialize(writer, myBasket, emptyNamespace);

            Console.WriteLine(output.ToString());

            // pause program execution to review results...
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
    }
}

它将序列化为此:

<Basket>
  <Fruit>Apple</Fruit>
  <Fruit>Orange</Fruit>
  <Fruit>Grapes</Fruit>
</Basket>

This is what the xml schema should look like:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Basket">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="Fruit" type="xs:string" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

If you save the xsd (let's just call it sample.xsd) and run xsd with the following parameters:

xsd.exe /c /n:BasketOfFruits sample.xsd

You will have this class:

namespace BasketOfFruits {
    using System.Xml.Serialization;


    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
    public partial class Basket {

        private string[] fruitField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("Fruit")]
        public string[] Fruit {
            get {
                return this.fruitField;
            }
            set {
                this.fruitField = value;
            }
        }
    }
}

Here's a sample program to demonstrate:

using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using BasketOfFruits;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Basket myBasket = new Basket();
            myBasket.Fruit = new string[] { "Apple", "Orange", "Grapes" };

            XmlSerializer xs = new XmlSerializer(typeof(Basket));            
            XmlSerializerNamespaces emptyNamespace = new XmlSerializerNamespaces();
            emptyNamespace.Add(String.Empty, String.Empty);

            StringBuilder output = new StringBuilder();

            XmlWriter writer = XmlWriter.Create(output, 
                new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true });
            xs.Serialize(writer, myBasket, emptyNamespace);

            Console.WriteLine(output.ToString());

            // pause program execution to review results...
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
    }
}

Which will serialize to this:

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