0

この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#で何にマップされますか?クラス?属性は何にマップされますか?プロパティ?私はこれを正しい方法で行っていますか?

4

2 に答える 2

1

XmlSerializerクラスと、XmlRootXmlElement、およびXmlAttribute属性を使用します。例えば:

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からオブジェクトに解析します。

于 2012-09-10T01:54:06.603 に答える
0

XML要素と属性は、特にC#では必ずしも何かにマップされるとは限りません。必要に応じて、クラスやプロパティにマップすることができますが、必須ではありません。

とはいえ、既存のXMLをある種のC#データ構造にマップする場合は、それを行う方法は合理的と思われます。パブリックフィールドを実際のプロパティに置き換え、リストプロパティを少なくすることをお勧めします。特定のタイプ-たとえば、IEnumerable、ICollection、またはIList(本当に順番に並べる必要がある場合)。

于 2012-09-09T23:55:52.607 に答える