如何通过一个XDocument的节点迭代 [英] How to iterate through an XDocument's Nodes

查看:214
本文介绍了如何通过一个XDocument的节点迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过我的XML文档的节点重复,以获得<的价值;用户名> ED< /用户名> 中的每个节点。我使用LINQ到第一类型的XDocument,然后通过节点试图循环。我似乎无法找到正确的foreach循环来实现这一点。 。任何帮助表示赞赏。



  VAR DOC = XDocument.Load(files\\config.xml); 
变种newDoc =新的XDocument(新的XElement(配置,从doc.Element(配置)p
。要素(档案)
排序依据int.Parse(第元素(命令)值)
选择p))。


的foreach(XE的XElement在newDoc.Nodes())
{
MessageBox.Show(xe.Element(用户名)值。);
}

// XML文档
<配置>
<&档案GT;
<&ID GT;适用范围和LT; / ID>
<用户名>适用范围1 LT; /用户名>
<密码和GT; ...< /密码>
<&CDKEY GT; 0000 LT; / CDKEY>
< expkey>< / expkey>
< cdkeyowner>适用范围和LT; / cdkeyowner>
<客户端> W2BN< /客户>
<服务器与GT; [IP] LT; /服务器>
< homechannel>大堂及LT; / homechannel>
<负荷大于1< /负载>
<排序> 2'; /排序>
< /档案>
<&档案GT;
<&ID GT;适用范围2'; / ID>
<用户名>适用范围2'; /用户名>
<密码和GT; ...< /密码>
<&CDKEY GT; 0000 LT; / CDKEY>
< expkey>< / expkey>
< cdkeyowner>适用范围和LT; / cdkeyowner>
<客户端> W2BN< /客户>
<服务器与GT; [IP] LT; /服务器>
< homechannel>大堂及LT; / homechannel>
<负荷大于1< /负载>
<排序> 1 LT; /排序>
< /档案>
< /配置>


解决方案

试试这个。不知道为什么你需要第二个文档。

 的foreach(在doc.Descendants的XElement XE(档案))
{
MessageBox.Show(xe.Element(用户名)值。);
}


I am trying to iterate through my xml document's nodes to get the value for <username>Ed</username> in each node. I am using Linq to sort the XDocument first, then attempting to loop through the nodes. I can't seem to find the correct foreach loop to achieve this. Any help is appreciated.

var doc = XDocument.Load("files\\config.xml");
var newDoc = new XDocument(new XElement("Config",
            from p in doc.Element("Config").Elements("Profile")
            orderby int.Parse(p.Element("order").Value)
            select p));


foreach (XElement xe in newDoc.Nodes())
{
    MessageBox.Show(xe.Element("username").Value);
}

// XML document
<Config>
<Profile>
    <id>Scope</id>
    <username>Scope 1</username>
    <password>...</password>
    <cdkey>0000</cdkey>
    <expkey></expkey>
    <cdkeyowner>Scope</cdkeyowner>
    <client>W2BN</client>
    <server>[IP]</server>
    <homechannel>Lobby</homechannel>
    <load>1</load>
    <order>2</order>
</Profile>
<Profile>
    <id>Scope 2</id>
    <username>Scope 2</username>
    <password>...</password>
    <cdkey>0000</cdkey>
    <expkey></expkey>
    <cdkeyowner>Scope</cdkeyowner>
    <client>W2BN</client>
    <server>[IP]</server>
    <homechannel>Lobby</homechannel>
    <load>1</load>
    <order>1</order>
</Profile>
</Config>

解决方案

Try this. Not sure why you need the second doc.

foreach (XElement xe in doc.Descendants("Profile"))
{
    MessageBox.Show(xe.Element("username").Value);
}

这篇关于如何通过一个XDocument的节点迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆