【问题标题】:Extracting XML values from two nodes从两个节点提取 XML 值
【发布时间】:2014-07-08 08:31:38
【问题描述】:

我想提取 moduleId 属性中的值和 Field 节点中的值。例如,在第一个节点中,我想提取 moduleId 中的 447 和 Field 节点中的 124694。我在 XDocument 中加载了 XML。最终结果将是一个 Tuple,其中第一项是 moduleId 属性的值,第二项是 Field 节点的值。有没有一种方法可以使用一个 Xlinq 语句来做到这一点?

作为奖励...我只想对 guid = "07a188d3-3f8c-4832-8118-f3353cdd1b73" 的节点执行此操作。这部分我可能会弄清楚是否有人可以告诉我如何从两个节点中提取信息,但额外的好处是为我添加 WHERE 子句:)

<Records>
    <Record moduleId="447">
        <Field guid="07a188d3-3f8c-4832-8118-f3353cdd1b73">124694</Field>           
    </Record>   
    <Record moduleId="447">
            <Field guid="07a188d3-3f8c-4832-8118-f3353cdd1b73">124699</Field>    
    </Record>
<Records>

我已经使用这个来提取字段值......

IEnumerable<string> c = from p in sourceDocument.Descendants("Field")
                        where p.Attribute("guid").Value == "07a188d3-3f8c-4832-8118-f3353cdd1b73"
                        select p.Value;

但我不知道如何从 Record 节点和 Field 节点获取信息。

【问题讨论】:

  • 你能用有效的 XML 更新你的帖子吗?这里有多个根元素。
  • 考虑编辑您的 XML 以正确关闭 &lt;Records&gt; 元素...结束标记缺少 /

标签: c# xml linq-to-xml


【解决方案1】:

试试这个:

var doc = XDocument.Parse(xml);
var r = doc.Descendants("Record")
    .Where(n => n.Element("Field").Attribute("guid").Value == "07a188d3-3f8c-4832-8118-f3353cdd1b73")
    .Select(n => new { ModuleId = n.Attribute("moduleId").Value, Field = n.Element("Field").Value });

var a = r.ToArray();

【讨论】:

  • 做到了……现在我看到它似乎很容易。谢谢!
【解决方案2】:

这是一个使用 LINQ 查询语法的解决方案:

XDocument document = XDocument.Parse(xml);

var query =
    from el in document.Root.Elements("Record")
    where (string)el.Element("Field").Attribute("guid") ==
        "07a188d3-3f8c-4832-8118-f3353cdd1b73"
    select new
    {
        ModuleId = (string)el.Attribute("moduleId"),
        Field = (string)el.Element("Field")
    };

foreach (var item in query)
{
    Console.WriteLine
        ("ModuleId:[{0}]\nField:[{1}]\n--",
             item.ModuleId,
             item.Field);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 2014-08-06
    • 2019-04-27
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    相关资源
    最近更新 更多