使用不同的键解析xml [英] Parse xml with varying Key

查看:82
本文介绍了使用不同的键解析xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析以下XML:

I'm trying to parse the XML below:

<plist version="1.0">
<array>
    <dict>
        <key>SubTitle</key>
        <array>
            <dict>
                <key>Values</key>
                <array>
                    <string>D1</string>
                    <string>D2</string>
                </array>
                <key>Title</key>
                <string>Chapter One</string>
                <key>supportsEdit</key>
                <true/>
            </dict>
            <dict>
                <key>Values</key>
                <array>
                    <string>DC1</string>
                    <string>DC2</string>
                </array>
                <key>Title</key>
                <string>Chapter Two</string>
                <key>supportsEdit</key>
                <true/>
            </dict>
        </array>
        <key>MainTitle</key>
        <string>Science</string>
    </dict>
    <dict>
        <key>SubTitle</key>
        <array>
            <dict>
                <key>Values</key>
                <array>
                    <string>CD1</string>
                    <string>CD2</string>
                </array>
                <key>Title</key>
                <string>Chapter One</string>
                <key>supportsEdit</key>
                <true/>
            </dict>
            <dict>
                <key>Values</key>
                <array>
                    <string>DDC1</string>
                    <string>DDC2</string>
                </array>
                <key>Title</key>
                <string>Chapter Two</string>
                <key>supportsEdit</key>
                <true/>
            </dict>
        </array>
        <key>MainTitle</key>
        <string>Physics</string>
    </dict>

    /// here is where i get the error
    <dict>
        <key>Values</key>
        <array>
                            <string>CD1</string>
                <string>CD2</string>
                            <string>DDC1</string>
            <string>DDC2</string>
                            <string>DC1</string>
                        <string>DC2</string>
        </array>
        <key>Title</key>
        <string>Random Values</string>
        <key>supportsEdit</key>
        <true/>
    </dict>

这是我的解析器:

XDocument doc = XDocument.Load(FileName);

Dictionary<string, List<Chapter>> plistData =
        doc.Root.Element("array").Elements("dict")
            .Select(GetValues)
            .ToDictionary(v => (string)v["MainTitle"],
                          v => v["SubTitle"]
                          .Elements("dict").Select(ParseMyObject).ToList());

static Dictionary<string, XElement> GetValues(XElement dict)
{
    return dict.Elements("key")
               .ToDictionary(k => (string)k, k => (XElement)k.NextNode);
}

static Chapter ParseMyObject(XElement dict)
{
    var values = GetValues(dict);

    return new Topic
    {
        Title = (string)values["Title"],
        FileNames = values["Values"].Elements().Select(s =>(string)s).ToList()
    };
}

请参阅我在XML文件中添加的注释.这里的问题是,前两个dict具有key作为SubTitlearray,但是第三个dict没有任何key.

Please see the comment that I have added in the XML file. The issue here is that the first two dicts have key as SubTitle with array but the third dict does not have any key.

我应该如何解析?

我正在Windows Phone 8上工作,并试图解析XML并在UI中填充数据.这是我的UI外观:我有3个按钮:科学",物理"和随机".

I am working on windows Phone 8 and am trying to parse the XML and populate the data in a UI. This is what my UI looks like: I have 3 buttons: Science, Physics and Random.

当我单击科学"时,将得到第一章和第二章";如果单击第一章或第二章,我将从XML中获取所有值.

When I click on "Science" I get "Chapter one and chapter two"; if I click on either chapter one or chapter two I get all values from the XML.

但是,当我单击随机"时,我只需要从XML中获取值即可.

But when I click on "Random" I need to get only values from the XML.

编辑

打印值:

foreach (var value in plistData)
{
    topicList.Add(value.Key);
    Debug.WriteLine(" Main title is "+value.Key);
    if (!value.Key.Equals("Random Values"))
    {
        List<Topic> listOfSubTopics = plistData[value.Key];
        for (int j = 0; j < listOfSubTopics.Count; j++)
        {
            Debug.WriteLine("sub title " + listOfSubTopics[j].Title);
            for (int i = 0; i < listOfSubTopics[j].FileNames.Count; i++)
            {
                Debug.WriteLine("Values is" + listOfSubTopics[j].FileNames[i]);
            }
        }
    }
    else
    {
       // here i want to print values of Random Values
    }

推荐答案

出于调试目的,我将您的收藏分为两个步骤:

For debugging purposes I split your collection in two steps:

        var first = doc
            .Root
            .Element("array")
            .Elements("dict")
            .Select(GetValues);

       var plistData = first
            .ToDictionary(
                v => v.ContainsKey("MainTitle")?
                        (string) v["MainTitle"]:
                        (string) v["Title"],
                 v => (v.ContainsKey("SubTitle")?
                        v["SubTitle"]
                        .Elements("dict")
                        .Select(ParseMyObject) :
                        ParseMyString(v["Values"])
                        )
                        .ToList());

最后一个plist结构的帮助器

    static List<Chapter> ParseMyString(XElement dict)
    {

        return new List<Chapter>
            {
                new Chapter
                    {
                        Title = "some values",
                        FileNames = dict.Elements().Select(s => (string) s).ToList()
                    }
            };
    } 

在创建字典元素时,我添加了一项检查,如果键 MainTitle 实际上存在.如果没有,我添加一个默认密钥.如果不存在null值,则对 SubTitle 采用相同的机制.

I added a check when you create the dictionary element if the key MainTitle actually exists. If it doesn't I add a default key. The same mechanism is applied to SubTitle, if that doesn't exist a null value is supplied.

这篇关于使用不同的键解析xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆