Linq to XML:提高性能
我想使用 Linq 读取 xml 文件。这个 xml 文件由 1 个标头和 N 个子元素组成,如下所示:
<rootNode>
<header>
<company name="Dexter Corp." />
</header>
<elements>
<element>one</element>
<element>eleven</element>
<element>three</element>
<element>four</element>
<element>five</element>
<element>three</element>
<element>two</element>
<element>two</element>
</elements>
</rootNode>
我想检索作为值的元素(例如:两个)。只有当我检索元素时,我才会得到标题元素。
今天,我确实喜欢这样:
string xmlFilePath = @"C:\numbers.xml";
XDocument doc = XDocument.Load(xmlFilePath);
var header = doc.Descendants().Elements("header");
var elements = doc.Descendants()
.Elements("elements")
.Elements("element")
.Where(el => el.Value == "two");
// I get this values even if there is no 'elements'
string companyName = header.Descendants("company").Attributes("name").Single().Value;
string serialNumber = header.Descendants("serial").Single().Value;
return elements.Select(el => new {Company = companyName, Serial = serialNumber, Value = el.Value});
有更好的方法来解析文件吗? (并提高性能?)
I want to read a xml file using Linq. This xml file is composed of 1 header and N Sub-Elements like this :
<rootNode>
<header>
<company name="Dexter Corp." />
</header>
<elements>
<element>one</element>
<element>eleven</element>
<element>three</element>
<element>four</element>
<element>five</element>
<element>three</element>
<element>two</element>
<element>two</element>
</elements>
</rootNode>
I want to retrieve elements which are a value (example : two). And only if I retrieve elements, I get the header elements.
Today, I do like this :
string xmlFilePath = @"C:\numbers.xml";
XDocument doc = XDocument.Load(xmlFilePath);
var header = doc.Descendants().Elements("header");
var elements = doc.Descendants()
.Elements("elements")
.Elements("element")
.Where(el => el.Value == "two");
// I get this values even if there is no 'elements'
string companyName = header.Descendants("company").Attributes("name").Single().Value;
string serialNumber = header.Descendants("serial").Single().Value;
return elements.Select(el => new {Company = companyName, Serial = serialNumber, Value = el.Value});
Is there a better way to parse the file ? (and increase performance ?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果性能对您来说很重要,则不应使用 doc.Descendants() 在某个已知位置查找元素。它始终扫描整个文档,如果文档很大,扫描速度会很慢。
相反,做类似
或
这样的事情应该会快得多。
If performance is important to you, you shouldn't use
doc.Descendants()
to look for an element at some known location. It always scans the whole document, which is slow if the document is big.Instead, do something like
or
That should be much faster.