C#查询XML文档 [英] C# Querying an XML Document

查看:51
本文介绍了C#查询XML文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天,

我正在尝试查询XML文档并具有以下查询:

I am trying to query an XML document and have the following query:

XElement root = XElement.Load(@"..\..\Data.xml");
var entries = root.Descendants()
              .Where(x => x.Name.LocalName == "Entry")
              .ToList();

Console.WriteLine("There are {0} nodes...", entries.Count());
foreach (XElement v in entries)
{
    Console.WriteLine(v.Value);
}

,此代码有效,因为它提取了正确数量的Entry节点.入口节点看起来像:

and this code works because it pulls the correct number of Entry nodes. The Entry nodes look like:

<?xml version="1.0" encoding="UTF-8"?>
<Database xmlns="http://www.someurl.org/schemas">
    <InfoFromRecord>
        <BaseData>
            <Entry>
                <Date>2006-03-08</Date>XD
                <Time>09:20:00</Time>
                <EnteredBy>DNS</EnteredBy>
                <TextEntry>Record 1</TextEntry>
            </Entry>
            <Entry>
                <Date>2006-03-08</Date>
                <Time>09:33:00</Time>
                <EnteredBy>MW</EnteredBy>
                <TextEntry>Record 2</TextEntry>
            </Entry>
            <Entry>
                <Date>2006-03-08</Date>
                <Time>08:58:00</Time>
                <EnteredBy>BH</EnteredBy>
                <TextEntry>Record 3</TextEntry>
            </Entry>
        </BaseData>
    </InfoFromRecord>
</Database>

问题是,我只想提取日期和时间,而不是全部四个字段.

The problem is, I want to extract only the Date and Time, not all four fields.

推荐答案

让我们假设您的整个XML文件如下所示:

Let's assume your entire XML file looks like this for a clear example:

<Entries>
    <Entry>
        <Date>2006-03-08</Date>
        <Time>09:33:00</Time>
        <EnteredBy>XX</EnteredBy>
        <TextEntry>Test Data</TextEntry>
    </Entry>
</Entries>

然后您可以执行以下操作:

You could then do something like this:

var document = XDocument.Load(@"..\..\Data.xml");
var dateAndTimes =
    from d in document.Root.Descendants("Entry")
    select new
                {
                    Date = d.Element("Date").Value,
                    Time = d.Element("Time").Value
                };

从此处, dateAndTimes 类型将选择一个日期和时间的匿名类型.您可以将匿名类型更改为您自己的类型,或其他.

From there, the dateAndTimes type will select an anonymous type of the Date and Time. You can change the anonymous type to be your own type, or something else.

编辑:问题是您的 xmlns .像这样更改代码:

EDIT: The problem is your xmlns. Change your code like so:

XNamespace namespc = "http://www.someurl.org/schemas";
var document = XDocument.Parse(xml);
var dateAndTimes =
    from d in document.Root.Descendants(namespc + "Entry")
    select new
                {
                    Date = d.Element(namespc + "Date").Value,
                    Time = d.Element(namespc + "Time").Value
                };

这篇关于C#查询XML文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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