最有效地使用 LINQ to XML
我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您与所需数据之间的元素越少越好。但使用 XML 结构的目的是为了理解数据。要问的一个问题是:是否有必要将每个人的地址分组在一起?如果是这样,那么有一个中间元素来描述分组是什么是值得的,例如:
如果不是,那么拥有中间元素就没有意义,并且它将花费您存储和解析它的开销。
如果您担心在代码中获取子元素集合是否容易,LINQ-to-XML 可以轻松处理这两种情况。例如:
您可以简单地提取您想要的内容:
这意味着您不需要像这样的中间元素。或,只有在需要引入覆盖子元素组的属性/元数据时才添加它们。
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:
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:
You can extract what you want trivially:
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.