使用XPathNavigator循环遍历XML文档

时间:2014-12-22 13:36:45

标签: c# .net xml xpath

我有以下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());

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

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

注意:它应该与您的查询完全相同Mailing而不是RESULT,并且应以/结尾