一个复杂的业务XML到Object在Silverlight中反序列化以统治它们

时间:2011-09-28 22:43:21

标签: c# silverlight serialization xml-serialization deserialization

我现在正在寻找一些时间教程并发布如何将复杂的XML文档反序列化为对象并在Silverlight应用程序中使用它。我已经看过很多2008年,2009年的教程和帖子,其中许多明显不起作用..使用Hello World或类“Person”很容易,但我找不到任何关于某些复杂xml文件的好东西和对数据的对象。 3行解析代码不是问题,但c#代码是什么样的?我如何创建所有这些类?如何使用这些对象?

让我们假设你从Web服务获得一个流,或者你的逻辑中有一个字符串。您有名称空间,属性和6个子节点。

<?xml version="1.0" encoding="UTF-8"?>
<om:root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:om="http://www.opengis.net/om/1.0">
<a name="a1">
<b>
    <c id="1" name="C1">
        <d id="1" name="D1">My name is D1</d>
        <d id="2" name ="D2">My name is D2</d>
        <e>
            <f>this is f1</f>
        </e>
    </c>
    <c id="2" name="C2">
        <d id="3" name="D3">My name is D3</d>
        <e>
            <f>this is f2</f>
        </e>
    </c>
</b>
<b>
    <c id="3" name="C3">
        <d id="4" name="D5">My name is D4</d>
        <d id="5" name="D5">My name is D5</d>
        <d id="6" name="D6">My name is D6</d>
        <d id="7" name="D7">My name is D7</d>
        <e>
            <f>this is f3</f>
        </e>
    </c>
</b>
</a>
</om:root>

1)是否有任何网站可以创建类和c#代码以便能够在xml中处理/存储数据?您发布了xml文件,并获取了c#类的源代码。像www.json2csharp.com这样的东西

2)我的课程,属性等如何?我希望看到一种标准的现代技术方式,如何处理属性,属性,列表等。完整的代码与“使用xxx”!请允许使用可与Silverlight一起使用的标准序列化程序类!

3)一些对象动作。像

  1. 在列表中给我所有nom:c
  2. 在nom中给我f的值:c id =“2”
  3. 将所有b放入列表
  4. 从name =“”FROM all test:d nodes
  5. 给我所有的atributevalues

    只是一些严格的实际查询而不是那些easymode get.me.person.name或book.name

    编辑:好的,也许这很难。任何人都可以发布一些链接,其中至少有一种教程或带有一些示例的博客?

2 个答案:

答案 0 :(得分:0)

要从xml生成c#类,您可以使用Microsoft工具xsd.exe

答案 1 :(得分:0)

我自己也是一个初学者,但如果我是你,我肯定会看看System.Xml.Linq类。当你已经弄清楚你的课程时,反序列化你的文档应该非常简单。在下面我粘贴了我的代码片段,它完全符合你的要求。它适用于WP7,但除了IsolatedStorage部分,一切都应该是相同的。

ItemTemplate item = new ItemTemplate();
        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("/Items.xml", FileMode.Open))
            {
                XElement doc = XElement.Load(stream);
                IEnumerable<XElement> itemTest = from el in doc.Elements("item")
                                                 where (string)el.Element("id") == itemId
                                                 select el;
                foreach (XElement el in itemTest)
                {
                    item.ItemContent = el.Element("content").Value;
                    item.Status = Convert.ToBoolean(el.Element("status").Value);
                    item.Notes = el.Element("notes").Value;
                    item.Location = el.Element("location").Value;
                    item.Deadline = Convert.ToDateTime(el.Element("deadline").Value);
                }                  
            }
        }