【问题标题】:XML Select Node into List FailXML 选择节点到列表失败
【发布时间】:2019-07-04 11:48:17
【问题描述】:

将简单的 XML 文件加载到 LIST 中没有问题。但是,当我创建第二个元素时,它会加载,但会将所有内容加载到一行中。

我什至尝试使用 xmlDoc.Descendants("apple") 获得相同的结果。

有效。

<?xml version="1.0" encoding="utf-8"?>
<green_apple>
    <Location>CA</Location>
    <Price>.52</Price>
</green_apple>

XDocument xmlDoc = XDocument.Load("apple.xml");
List<string> list = xmlDoc.Root.Elements()
                    .Select(element => element.Value.Trim())
                    .ToList();

List Result:
list[0] = CA
List[1] = .52

不起作用。

<?xml version="1.0" encoding="utf-8"?>
<apple>
    <green_apple>
        <Location>CA</Location>
        <Price>.52</Price>
    </green_apple>
    <red_apple>
        <Location>FL</Location>
        <Price>.71</Price>
    </red_apple>
</apple>

XDocument xmlDoc = XDocument.Load("apple.xml");
            List<string> list = xmlDoc.Root.Elements("green_apple")   <<specify specify element.
                .Select(element => element.Value.Trim())
                .ToList();

List Result:
list[0] = CA.52   <<Here's the problem, they should be in their own list element.

【问题讨论】:

    标签: c# .net xml xpath


    【解决方案1】:

    Elements 重新调整当前节点的子元素,在您的情况下是 green_apple 元素。所以你需要通过在green_apple元素上调用Elements()来获取green_apple子节点。

    使用这个:

    List<string> list = xmlDoc.Root.Elements("green_apple").Elements()
                    .Select(element => element.Value.Trim())
                    .ToList();
    

    【讨论】:

    • @Kirill....你就是那个男人。谢谢你。我花了 2 个小时,不敢相信我错过了 extra.Element()。
    • @Pirate,有时候有一双额外的眼睛真是太好了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    相关资源
    最近更新 更多