【问题标题】:How to iterate through an XDocument's Nodes如何遍历 XDocument 的节点
【发布时间】:2011-02-14 07:16:12
【问题描述】:

我正在尝试遍历我的 xml 文档的节点以获取每个节点中 <username>Ed</username> 的值。我首先使用 Linq 对 XDocument 进行排序,然后尝试遍历节点。我似乎找不到正确的 foreach 循环来实现这一点。任何帮助表示赞赏。

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>

【问题讨论】:

  • 您能发布您的(删节的)架构或(删节的)示例文件吗?
  • 当然,codeEdEd 2code
  • 您应该能够在此处放置断点,在调试模式下运行,然后检查 newDoc 对象以确定要查询的正确 XML 属性。
  • 将架构添加到您的问题而不是评论中,它会更容易参考
  • 抱歉,我已将其添加到问题中。

标签: c# .net xml linq sorting


【解决方案1】:

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

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

【讨论】:

  • 第二个文档是在我的架构中按code 对第一个文档进行排序,我只是没有包含它。这可行,但是有没有办法循环每个节点并获取节点中所有元素的值? (我的架构被缩短了,每个节点包含大约 10 个我需要访问的元素)。
  • 发布完整的架构,或者尽可能多的相关。否则,很难猜出你想要完成什么
  • 发布了完整的架构。基本上我需要遍历每个 code 节点并获取其中每个元素的值。
  • 通过将 .Descendants("username") 更改为 .Descendants("Profile") 使其工作。不知道为什么我以前没有看到。感谢您的帮助。
  • stackoverflow.com/questions/49014192/… 的任何帮助将不胜感激。
【解决方案2】:

使用 XPathDocument 和 XPath 表达式更容易。

var doc = new XPathDocument("files\\config.xml")
foreach (var username in doc.CreateNavigator().Select("//username")
{
    ...
}

【讨论】:

    【解决方案3】:

    如果您正在寻找内部节点,即类似递归,您可以检查元素是否有元素。 例如假设你从数据库中读取你的 xml

    string xmlRoot = "select XmlItem from db";
    XDocument doc = XDocument.Parse(xmlRoot);
    List<XElement> xElementList = doc.Descendants().ToList();
    foreach(XElement element in xElementList )
    {
      // read the element and do with your node
      if(element.HasElements)
        {
          // here you can reach nested node
        }
    
    } 
    

    【讨论】:

      猜你喜欢
      • 2012-06-17
      • 2011-09-09
      • 1970-01-01
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多