按名称提取 XElement 子代和孙代
我有一个 XElement (myParent),其中包含我希望从中提取数据的多个子级。感兴趣的元素位于父元素的已知位置。
我知道我可以通过以下方式获取子元素:
myParent.Element(childName);
或者,
myParent.Element(level1).Element(childName);
如果我想循环遍历不同级别的元素列表的数组,并循环遍历列表,那么我很难弄清楚如何执行此操作。例如,我有兴趣获取以下元素集:
myParent.Element("FieldOutputs").Element("Capacity");
myParent.Element("EngOutputs").Element("Performance")
myParent.Element("EngOutputs").Element("Unit").Element("Efficiency")
如何在数组中定义这些位置,以便可以简单地循环遍历数组?
即
string[] myStringArray = {"FieldOutputs.Capacity", "EngOutputs.Performance", "EngOutputs.Unit.Efficiency"};
for (int i=0; i< myArray.Count(); i++)
{
XElement myElement = myParent.Element(myStringArray);
}
我知道上面的方法不起作用,但只是想有效地展示我想要实现的目标。
如有任何反馈,我们将不胜感激。
谢谢你, 贾斯汀
I have an XElement (myParent) containing multiple levels of children that I wish to extract data from. The elements of interest are at known locations in the parent.
I understand that I am able to get a child element by:
myParent.Element(childName);
or
myParent.Element(level1).Element(childName);
I am having trouble figuring out how to do this if I want to loop through an array offor a list of elements that are at different levels, and looping through the list. For instance, I am interested in getting the following set of elements:
myParent.Element("FieldOutputs").Element("Capacity");
myParent.Element("EngOutputs").Element("Performance")
myParent.Element("EngOutputs").Element("Unit").Element("Efficiency")
How can I define these locations in an array so that I can simply loop through the array?
i.e.
string[] myStringArray = {"FieldOutputs.Capacity", "EngOutputs.Performance", "EngOutputs.Unit.Efficiency"};
for (int i=0; i< myArray.Count(); i++)
{
XElement myElement = myParent.Element(myStringArray);
}
I understand that the method above does not work, but just wanted to show effectively what I am trying to achieve.
Any feedback is appreciated.
Thank you,
Justin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然通常我不愿意建议使用 XPath,但这可能是最合适的方法,使用
XPathSelectElement
:While normally I'm reluctant to suggest using XPath, it's probably the most appropriate approach here, using
XPathSelectElement
:我相信,
Descendants()
方法就是您正在寻找的方法。例如:http://msdn.microsoft。 com/en-us/library/system.xml.linq.xelement.descendants.aspx
编辑:
更仔细地查看您的问题,看起来您可能想要使用 XPathSelectElements()
<一href="http://msdn.microsoft.com/en-us/library/bb351355.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb351355.aspx
The
Descendants()
method is what you're looking for, I believe. For example:http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.descendants.aspx
Edit:
Looking at your question more closely, it looks like you may want to use XPathSelectElements()
http://msdn.microsoft.com/en-us/library/bb351355.aspx