0

我正在尝试读取具有以下 C# 中给出的以下格式的 xml。我必须将每个 sql 文本和邮件正文内容以及客户标签下的每个电子邮件地址存储到一个字符串变量中以供进一步处理。我在下面给出的 XML 格式

    <?xml version="1.0" encoding="utf-8" ?>
<Queries>
    <Customer>
        <SQL ID="GYSQL">
            Select * from customer where code ='GYSQL'
        </SQL>
        <MailBody>
              Please find  the Report GY
        </MailBody>
        <Address>customer1@mail.com</Address>
        <Address>customer2@mail.com</Address>
    </Customer>
    <Customer>
        <SQL ID="TSSQL">
            Select * from customer where code ='TSSQL'
        </SQL>
        <MailBody>
              Please find  the Report TS
        </MailBody>
        <Address>customer3@mail.com</Address>
        <Address>customer4@mail.com</Address>
        <Address>customer5@mail.com</Address>
    </Customer>
</Queries>

我必须遍历每个客户标签

  var xml = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\xml\\sql.xml";
                XmlDocument xml1 = new XmlDocument();
                xml1.Load(xml);
                XmlNodeList list = xml1.SelectNodes(@"//Customer");
                foreach (XmlNode xn in list)
                {
                    
                    string Sql = Get the text from SQL tag under Customer
                    string mailbody = Get the text under tag Customer\Mailbody
                    //Here I have to get each email address in a loop in a string variable

                }
 
4

1 回答 1

1

要继续使用 XPath 表达式,您可以执行以下操作:

foreach (XmlNode xn in list)
{   
    // Find the first child node of 'xn' with name "SQL"
    var sqlForThisCustomer = xn.SelectSingleNode("SQL")?.InnerText;
    // Same for "MailBody"
    var mailBodyForThisCustomer = xn.SelectSingleNode("MailBody")?.InnerText;   

    var addressList = xn.SelectNodes("Address");
    foreach(XmlNode adr in addressList) {
        var currentAddress = adr.InnerText;     
    }
}

对于这类工作,我通常更喜欢XDocument

var doc = XDocument.Parse(xmlstring);
var customers = doc.Root
            .Elements("Customer")
            .Select(c => new {
                SQL = c.Element("SQL")?.Value,
                MailBody = c.Element("MailBody")?.Value,
                Addresses = c.Elements("Address").Select(x => x.Value).ToList()
            })
            .ToList();
于 2020-12-03T10:56:26.513 回答