最有效地使用 LINQ to XML

发布于 2024-10-12 21:01:03 字数 212 浏览 1 评论 0原文

我正在使用 LINQ to XML 来解析 XML 文档。我还有能力影响 XML 模式的设计。给定的 XML 元素 Person 可能有一个或多个 Address 元素作为子元素。解析时定义 XML 以便 Person 包含一个或多个 Address 节点会更有效吗?还是让 Person 包含一个 Addresses 节点(而该 Addresses 节点又包含一个或多个 Address 节点)会更好?谢谢。

I'm using LINQ to XML to parse an XML document. I also have the ability to influence the design of the XML schema. A given XML element, Person, may have one or more Address elements as children. Would it be more efficient when parsing to have the XML defined so that Person contains one or more Address nodes or would it be better for Person to contain an Addresses node that in turn contained one or more Address nodes? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

感情洁癖 2024-10-19 21:01:03

您与所需数据之间的元素越少越好。但使用 XML 结构的目的是为了理解数据。要问的一个问题是:是否有必要将每个人的地址分组在一起?如果是这样,那么有一个中间元素来描述分组是什么是值得的,例如:

<Person>
    <Addresses Group="Summer">
        <Address Street="123 Street Name" .../>
    </Addresses>

    <Addresses Group="Winter">
        <Address Street="456 Other Street" .../>
    </Addresses>
</Person>

如果不是,那么拥有中间元素就没有意义,并且它将花费您存储和解析它的开销。

如果您担心在代码中获取子元素集合是否容易,LINQ-to-XML 可以轻松处理这两种情况。例如:

<Person>
    <Address .../>
    <Address .../>
    <Phone .../>
    <Phone .../>
    <Email .../>
</Person>

您可以简单地提取您想要的内容:

var Addresses = personElement.Elements("Address");
var PhoneNumbers = personElement.Elements("Phone");

这意味着您不需要像这样的中间元素。或,只有在需要引入覆盖子元素组的属性/元数据时才添加它们。

The fewer elements between you and the desired data, the better. But the point of using the structure of XML is to make sense of the data. One question to ask is: will it be necessary to group addresses together under each person? If so, then it pays to have an intermediate element to describe what the grouping is, eg:

<Person>
    <Addresses Group="Summer">
        <Address Street="123 Street Name" .../>
    </Addresses>

    <Addresses Group="Winter">
        <Address Street="456 Other Street" .../>
    </Addresses>
</Person>

If no, then there's no point in having the intermediate element, and it will cost you the overhead of storing and parsing it.

If you're worried about how easy it will be to get collections of child elements in your code, LINQ-to-XML makes it easy to deal with either scenario. For example:

<Person>
    <Address .../>
    <Address .../>
    <Phone .../>
    <Phone .../>
    <Email .../>
</Person>

You can extract what you want trivially:

var Addresses = personElement.Elements("Address");
var PhoneNumbers = personElement.Elements("Phone");

This means you don't need to have intermediate elements like <Phones> or <EmailAddresses>, you'd only add them if it was necessary to introduce attributes/metadata covering groups of child elements.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文