使用 XPathNavigator 循环遍历 XML 文档

本文关键字:XML 文档 遍历 循环 XPathNavigator 使用 | 更新日期: 2023-09-27 18:34:53

>我有下面的XML,我正在尝试将值写入CSV文件。但是,我不确定如何继续,我尝试过的所有内容都抛出错误。下面返回:"表达式必须计算到节点集"。任何帮助将不胜感激。

.XML:

<?xml version="1.0" encoding="UTF-8"?>
<Envelope>
   <Body>
  <RESULT>
     <SUCCESS>TRUE</SUCCESS>
     <Mailing>
        <MailingId>9285984</MailingId>
        <ReportId>362040252</ReportId>
        <ScheduledTS>2014-08-22 11:44:33.0</ScheduledTS>
        <MailingName>305_ENDS</MailingName>
     </Mailing>
     <Mailing>
        <MailingId>9278770</MailingId>
        <ReportId>361956135</ReportId>
        <ScheduledTS>2014-08-22 09:15:00.0</ScheduledTS>
        <MailingName>141_TSI</MailingName>
        <Visibility>Shared</Visibility>
     </Mailing>
     <Mailing>
        <MailingId>9286460</MailingId>
        <ReportId>362043622</ReportId>
        <ScheduledTS>2014-08-22 12:57:30.0</ScheduledTS>
        <MailingName>301_BRANDREP</MailingName>
     </Mailing>
  </RESULT>
</Body>
</Envelope>

C#:

xpathDoc = HttpHelper.HttpStream(xmlReq, sessionid);
XPathNavigator nav = xpathDoc.CreateNavigator();
XPathNodeIterator xmlIterator = nav.Select("/Envelope/Body/RESULT/");
var csv = new StringBuilder();
filePath = "C:'Campaigns.csv";
foreach (XPathNavigator node in xmlIterator)
{
string MailingId = node.SelectSingleNode("MailingId").Value;
string ReportId = node.SelectSingleNode("ReportId").Value;
string ScheduledTS = node.SelectSingleNode("ScheduledTS").Value;
string MailingName = node.SelectSingleNode("MailingName").Value;
string newLine = string.Format("{0},{1},{2},{3},{4}", MailingId, ReportId, ScheduledTS, MailingName, Environment.NewLine);
csv.Append(newLine);
}
File.WriteAllText(filePath, csv.ToString());

使用 XPathNavigator 循环遍历 XML 文档

好吧,您可以尝试以下方法:

foreach (XPathNavigator node in nav.Select("/Envelope/Body/RESULT/Mailing"))
{
    string MailingId = node.SelectSingleNode("./MailingId").Value;
    // and so on

注意:它应该完全Mailing而不是像查询中那样RESULT,并且不应该/结尾

XPathNavigator node in nav.Select("/Envelope/Body/RESULT/")更改为 XPathNavigator node in nav.Select("/Envelope/Body/RESULT/Mailing"),然后使用 例如 string MailingId = node.SelectSingleNode("MailingId").Value; .