C# 如何获取没有子元素的元素?
以下是我的xml:C# 如何获取没有子元素的元素?,c#,xml,linq,linq-to-xml,C#,Xml,Linq,Linq To Xml,以下是我的xml: 123 456 789 12 13 2. 3. 此xml文档非常大,大小可能为1GB或更大。为了提高查询性能,我想一步一步地阅读xml文档。所以,在第一步中,我只想读取“第一个孩子”及其属性,如下所示: 2. 3. 在那之后,我可能想通过他们父母的身份证得到“第二个孩子”,所以。。。 12 13 我怎么做 注意:XDoc.subjects()或XDoc.Elements()加载所有特定元素和所有子元素 如果您有内存来保存该文件,我建议将每个搜索步骤视为PLINQ
123
456
789
12
13
2.
3.
此xml文档非常大,大小可能为1GB或更大。为了提高查询性能,我想一步一步地阅读xml文档。所以,在第一步中,我只想读取“第一个孩子”及其属性,如下所示:
2.
3.
在那之后,我可能想通过他们父母的身份证得到“第二个孩子”,所以。。。
12
13
我怎么做
注意:XDoc.subjects()或XDoc.Elements()加载所有特定元素和所有子元素 如果您有内存来保存该文件,我建议将每个搜索步骤视为PLINQ管道外部集合中的一个项目 我将从要检索的节点集合的
XName
集合开始。通过在XElement
构造函数中嵌套查询,您可以返回目标节点的新实例,其中只包含名称和属性信息
使用.Where(…)
语句或两个语句,您还可以过滤保留的属性,允许保留一些子节点,等等
使用System.Collections.Generic;
使用System.Linq;
使用System.Xml.Linq;
名称空间LinqToXmlExample
{
公共课程
{
公共静态void Main(字符串[]args)
{
XElement root=XElement.Load(“[此处的文件路径]”);
XName[]name=新的XName[]{“第一个孩子”、“第二个孩子”、“第三个孩子”};
可数元素=
names.AsParallel()
.选择(
名称=>
新元素(
$“结果{name}”,
根目录。子目录(名称)
.天冬酰胺()
.选择(
x=>new-XElement(名称,x.Attributes()))
.ToArray();
}
}
}
在VB中,您可以这样做以获得第一个孩子的列表
'Dim yourpath As String = "your path here"
Dim xe As XElement
'to load from a file
'xe = XElement.Load(yourpath)
'for testing
xe = <Root>
<FirstChild id="1" att="a">
<SecondChild id="11" att="aa">
<ThirdChild>123</ThirdChild>
<ThirdChild>456</ThirdChild>
<ThirdChild>789</ThirdChild>
</SecondChild>
<SecondChild id="12" att="ab">12</SecondChild>
<SecondChild id="13" att="ac">13</SecondChild>
</FirstChild>
<FirstChild id="2" att="b">2</FirstChild>
<FirstChild id="3" att="c">3</FirstChild>
</Root>
Dim ie As IEnumerable(Of XElement)
ie = xe...<FirstChild>.Select(Function(el)
'create a copy
Dim foo As New XElement(el)
foo.RemoveNodes()
Return foo
End Function)
“将您的路径设置为String=“此处的您的路径”
弱xe-As-XElement
'从文件加载
'xe=XElement.Load(您的路径)
"测试",
xe=
123
456
789
12
13
2.
3.
(指元素)可数的尺寸
ie=xe…选择(功能(el)
'创建副本
Dim foo作为新XElement(el)
foo.RemoveNodes()
返回foo
终端功能)
我想XDoc.subjections(“FirstChild”)
会做你想做的事,如果你事先知道名字的话。是的!但是这个函数加载所有的子元素!你是如何加载文件的?我假设您使用的是XDocument
,而不是XmlDocument
。如果您调用了XDocument.Load()
,那么使用substands()
与substands(“FirstChild”)
应该没有关系。下面是一个可能会有很大帮助的示例。在当今世界,我不认为1GB的文档太大而无法在内存中处理,而且,从上到下多次重读文档的效率不如一次阅读并处理您遇到的所有内容。在文件系统上,XML文件只是一个文本文件,它是按顺序读取和处理的。XMLReader类将帮助您做到这一点,但如果您只通过一次,它仍然是最有效的。
'Dim yourpath As String = "your path here"
Dim xe As XElement
'to load from a file
'xe = XElement.Load(yourpath)
'for testing
xe = <Root>
<FirstChild id="1" att="a">
<SecondChild id="11" att="aa">
<ThirdChild>123</ThirdChild>
<ThirdChild>456</ThirdChild>
<ThirdChild>789</ThirdChild>
</SecondChild>
<SecondChild id="12" att="ab">12</SecondChild>
<SecondChild id="13" att="ac">13</SecondChild>
</FirstChild>
<FirstChild id="2" att="b">2</FirstChild>
<FirstChild id="3" att="c">3</FirstChild>
</Root>
Dim ie As IEnumerable(Of XElement)
ie = xe...<FirstChild>.Select(Function(el)
'create a copy
Dim foo As New XElement(el)
foo.RemoveNodes()
Return foo
End Function)