【问题标题】:Xdocument, get each element(s) valueXdocument,获取每个元素的值
【发布时间】:2023-04-07 22:53:01
【问题描述】:

我的xml如下:

<Reports>
  <report>
    <name>By Book</name>
    <report_type>book</report_type>
    <Object>Count Change</Object>
    <Slicers detail="detail">
      <Namespace>EOD</Namespace>
      <BookNode>HighLevel</BookNode>
      <DateFrom>T-2</DateFrom>
      <DateTo>T-1</DateTo>
      <System>NewSystem</System>
    </Slicers>
  </report>
</Reports>

我只是想遍历 Xdocument 的每个元素的值(pref 可以是 Slicers 下的任何元素),但只从所有元素开始。

当我运行以下命令时:

        var slicers = from c in config.Elements("Reports")
                      select c.Value ;

        foreach (var xe in slicers)
        {
            Console.WriteLine(xe);
        }

输出是将所有值连接在一起的单行。

“按 BookbookCount 更改 EODHighLevelT-2T-1NewSystem”

我想一次循环浏览它们,首先是“按书”,然后运行一些代码,然后进行预订等。

我确信这很简单,但无法绕过它。我试过 foreach(Xelement in query) 但结果相同

【问题讨论】:

  • 那是因为您只是打印根节点的值(即其中的所有内容)。尝试通过后代
  • 你能给我举个例子吗?我已经尝试了以下相同的结果var slicers = from c in config.Descendants("Reports") select c.Value;

标签: c# linq linq-to-xml


【解决方案1】:

我会这样做;

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
//load in your xml here
XmlNodeList xnList = doc.SelectNodes("nodeYou'reLookingFor");
//for getting just the splicers you could do "Reports/report/Slicers"

foreach (XmlNode node in xnList)
    string namespace = node["Namespace"].InnerText;
    //go through all your nodes here

您正在创建一个 xmldoc,将您的 xml 加载到其中,创建一个包含列表中每个节点的列表(在指定的 Xpath 处),然后循环遍历每个节点。在循环中,您可以通过引用来做任何您想做的事情

 node["nodenamehere"].InnerText

【讨论】:

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