如何提取XML文件中每个标记的出现

时间:2014-06-17 15:53:17

标签: c# xml linq

我有以下XML文件:

<queryResponse xmlns="">
    <querySubjectResponse xmlns="">
        ...
        <report>
            <informationReported>
                <aar>
                    <narrative>THIS IS A TEST NARRATIVE</narrative>
                </aar>
            </informationReported>
            ...
            <statement>
                <subjectStatement>
                    <statement>THIS IS A TEST STATEMENT</statement>
                </subjectStatement>
            </statement>
            ...
        </report>
        ...
        <report>
            <informationReported>
                <aar>
                    <narrative>THIS IS A TEST NARRATIVE2</narrative>
                </aar>
            </informationReported>
            ...
            <statement>
                <subjectStatement>
                    <statement>THIS IS A TEST STATEMENT2</statement>
                </subjectStatement>
            </statement>
            ...
        </report>
        ...
        <report>
            <informationReported>
                <aar>
                    <narrative>THIS IS A TEST NARRATIVE3</narrative>
                </aar>
            </informationReported>
            ...
            <statement>
                <subjectStatement>
                    <statement>THIS IS A TEST STATEMENT3</statement>
                </subjectStatement>
            </statement>
            ...
        </report>
        ...
    </querySubjectResponse>
</queryResponse>

我正在研究LINQ to XML,但我不确定如何实现它。我想保存叙述,并为每个叙述,将语句保存为一个数组,以便以后使用。

示例:

THIS IS A TEST NARRATIVE
THIS IS A TEST STATEMENT

THIS IS A TEST NARRATIVE2
THIS IS A TEST STATEMENT2

THIS IS A TEST NARRATIVE3
THIS IS A TEST STATEMENT3

我如何实现它?

我正在使用XDocument加载文件:

XDocument X = XDocument.Load("myfile.xml");
var main = x.Element("queryResponse").Element("querySubjectResponse").Element("report").Element("informationReported").Element("aar");

我正在尝试按照此链接的答案:Linq to XML

1 个答案:

答案 0 :(得分:3)

这应该对你有用,假设每个报告都有一个叙述和一个可选的陈述:

XElement root = XElement.Load(file);
List<string> list = root.Descendants("report")
    .SelectMany(report =>
    {
        List<string> sub = new List<string>();
        sub.Add(report.Descendants("narrative").First().Value);
        string statement = (string)report.Descendants("statement")
                        .FirstOrDefault(s => s.Elements().Any() == false);
        sub.Add(statement ?? "NULL");
        return sub;
    })
    .ToList();

如果您想将叙述和陈述放在单独的列表中,请改为:

var list = root.Descendants("report")
    .Select(report => new
    {
        Narrative = report.Descendants("narrative").First().Value,
        Statement = ((string)report.Descendants("statement")
                        .FirstOrDefault(s => s.Elements().Any() == false))
                    ?? "NULL"
    })
    .ToList();