繁体   English   中英

C#中的XML元素和属性等效项是什么?

[英]What are XML element and attribute equivalents in C#?

我试图基于此XML定义C#对象:

<UPDs LUPD="86">
  <UPD ID="106">
    <ER R="CREn">
      <NU UID="1928456" />
      <NU UID="1886294" />
      <M>
        <uN>bob · </uN>
        <mO>fine :D</mO>
      </M>

到目前为止,我有:

public class UDPCollection    
{
    List<UDP> UDPs; 

    public UDPCollection()
    {
        UDPs = new List<UDP>();
    }
}

public class UDP
{
    public int Id;
    public List<ER> ERs;
    public UDP(int id, List<ER> ers)
    {
        Id = id;
        ERs = ers;
    }
}

public class ER
{
    public string LanguageR;

    public ER(string languager)
    {
        LanguageR = languager;
    }
}

我的问题:在C#中元素映射到什么? 上课吗 属性映射到什么? 属性? 我要用正确的方法吗?

使用XmlSerializer类和XmlRootXmlElementXmlAttribute属性。 例如:

using System.Xml.Serialization;

...

[XmlRoot("UPDs")]
public class UDPCollection
{
    // XmlSerializer cannot serialize List. Changed to array.
    [XmlElement("UPD")]
    public UDP[] UDPs { get; set; }

    [XmlAttribute("LUPD")]
    public int LUPD { get; set; } 

    public UDPCollection()
    {
        // Do nothing
    }
}

[XmlRoot("UPD")]
public class UDP
{
    [XmlAttribute("ID")]
    public int Id { get; set; }

    [XmlElement("ER")]

    public ER[] ERs { get; set; }

    // Need a parameterless or default constructor.
    // for serialization. Other constructors are
    // unaffected.
    public UDP()
    {
    }

    // Rest of class
}

[XmlRoot("ER")]
public class ER
{
    [XmlAttribute("R")]
    public string LanguageR { get; set; }

    // Need a parameterless or default constructor.
    // for serialization. Other constructors are
    // unaffected.
    public ER()
    {
    }

    // Rest of class
}

编写XML的代码是:

using System.Xml.Serialization;

...

// Output the XML to this stream
Stream stream;

// Create a test object
UDPCollection udpCollection = new UDPCollection();
udpCollection.LUPD = 86;
udpCollection.UDPs = new []
{
    new UDP() { Id= 106, ERs = new [] { new ER() { LanguageR = "CREn" }}}
};

// Serialize the object
XmlSerializer xmlSerializer = new XmlSerializer(typeof(UDPCollection));
xmlSerializer.Serialize(stream, udpCollection);

并非XmlSerializer添加了其他名称空间,但是如果需要,它可以解析XML而无需它们。 上面的输出是:

<?xml version="1.0"?>
<UPDs xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns:xsd="http://www.w3.org/2001/XMLSchema" LUPD="86">
    <UPD ID="106">
       <ER R="CREn" />
    </UPD>
</UPDs>

使用Deserialize()方法将其从XML解析为一个对象。

XML元素和属性不一定映射到C#中的任何东西。 您可以根据需要使它们映射到类和属性,但这不是必需的。

就是说,如果您想将现有的XML映射到某种C#数据结构,那么您这样做的方式似乎是合理的-我只建议您用实际属性替换您的公共字段,也许可以减少列表属性特定类型-例如IEnumerable,ICollection或IList(如果确实需要按顺序排列)。

暂无
暂无

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

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