簡體   English   中英

XmlSerializer按名稱空間過濾

[英]XmlSerializer filter by namespace

我正在嘗試反序列化RSS 2.0 feed,並且我想考慮一些iTunes擴展,但不必直接將它們烘焙到主類中。

使用C#中的XML反序列化器,可能會出現以下情況?

public class RssChannel
{
    [XmlElement("title")]
    public string Title { get; set; }

    [XmlElement("link")]
    public string Link { get; set; }

    ....

    [XmlElement(Namespace = "itunes")]
    public iTunesExtensions iTunes { get; set; }
}

public class iTunesExtensions 
{
    [XmlElement("category")]
    public string[] Categories { get; set; }
}

我希望可以解析如下內容:

<channel>
    <itunes:category text="Society & Culture"/>
    <itunes:category text="Society & Culture"/>
    <itunes:category text="Society & Culture"/>
</channel>

可以在模塊化程度更高的地方做類似的事情嗎? 還是我堅持將其烘焙到主要班級?

bizzehdee,

為了將第一級設置為“”,您需要將其設置為類的根目錄和名稱:

[XmlRoot("channel")]
public class channel

對於以下示例,我將其保留為RssChannel。

我假設您打算使用比iTunes更多的平台,所以iTunes仍然有自己的類。 使用較少的代碼即可完成此操作的方法是使用列表而不是數組:

public List<iTunes> iTunes;

類別將具有自己的類,因此您可以在任何平台上使用類別。 注意XmlAttribute的使用。 這將在同一行中包含類別名稱:

public class iTunes 
{
    public List<Category> Categories { get; set; }
}

public class Category
{
    [XmlAttribute("category")]
    public string category { get; set; }
}

您可以使用靜態類來幫助您序列化和反序列化數據。 靜態類中的以下兩種方法會有所幫助:

// Save XML data.
public static void SaveData(ref RssChannel instance) {}

// Retrieve XML data.
public static RssChannel DeserializeData() {}

使用這些方法的最佳方法是首先使用DeserializeData()方法獲取RssChannel的實例,例如:

RssChannel foo = StaticClassName.DeserializeData();

對其進行更改,然后通過將其作為對SaveData()方法的引用進行傳遞來保存該實例,例如:

SaveData(ref foo);

這是一個完整的工作示例:

public static class XML
{
    // Serializes the passed instance of RssChannel into XML file, and saves to runtime memory.
    public static void SaveData(ref RssChannel instance)
    {
        // Objects:
        StreamWriter sw = new StreamWriter("yourXmlFile.xml");
        XmlSerializer serializer = new XmlSerializer(typeof(RssChannel));

        // Save data.
        serializer.Serialize(sw, instance);
        sw.Close();
    }

    // Deserializes data from the XML file, and returns the instance.
    public static RssChannel DeserializeData()
    {
        // Objects:
        RssChannel channelData = new RssChannel();
        XmlSerializer serializer = new XmlSerializer(typeof(RssChannel));
        List<iTunes> iTunesList = new List<iTunes>();

        if (File.Exists("yourXmlFile.xml"))
        {
            FileStream stream = new FileStream("yourXmlFile.xml", FileMode.Open);

            // Deserialize data.
            channelData = (RssChannel)serializer.Deserialize(stream);
            stream.Close();

            // Add data from deserialized iTunes list to list instance.
            if (channelData.iTunesList != null)
                iTunesList = channelData.iTunesList;
        }

        // Add data to RootData object lists.
        channelData.iTunesList = iTunesList;

        return channelData;
    }
}

[XmlRoot("RssChannel")]
public class RssChannel
{
    [XmlAttribute("Title")]
    public string Title; // { get; set; }

    [XmlAttribute("Link")]
    public string Link; // { get; set; }

    public List<iTunes> iTunesList; // { get; set; }
}

public class iTunes 
{
    public List<Category> Categories; // { get; set; }
}

public class Category
{
    [XmlAttribute("category")]
    public string category; // { get; set; }
}

您可以使用這樣的類和靜態方法:

private void AnyMethod()
{
    // To get an instance of your RssChannel class with all the data:
    RssChannel rssChannel = XML.DeserializeData();

    // Do anything with the data. Example below:
    iTunes newITunes = new iTunes();
    List<Category> categoryList = new List<Category>();

    Category newCategory1 = new Category(); // Create new categories.
    newCategory1.category = "Allegro";
    categoryList.Add(newCategory1);

    Category newCategory2 = new Category();
    newCategory2.category = "Prestissimo";
    categoryList.Add(newCategory2);

    newITunes.Categories = categoryList; // Add the categories to list.

    rssChannel.iTunesList.Add(newITunes); // Add that list to iTunes list.

    // Now, to save the data, pass a reference to the instance we just worked on:
    XML.SaveData(ref rssChannel);
}

這將產生一個如下文件:

<?xml version="1.0" encoding="utf-8"?>
<RssChannel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <iTunesList>
    <iTunes>
      <Categories>
        <Category category="Allegro" />
        <Category category="Prestissimo" />
      </Categories>
    </iTunes>
  </iTunesList>
</RssChannel>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM