解析从WebRequest返回的XML字符串

时间:2018-11-20 22:32:37

标签: c# xml parsing

我有一个HTTPWebRequest返回的xml字符串,我需要对其进行解析以获得正确的邮寄地址。标签包含一个子标签,其子标签可以是Primary或​​Alternate。如果标记等于Alternate,则将使用该CustAddr的地址值,但是如果没有Alternate,则将使用Primary作为默认值。在C#中,如何使用System.Xml.Linq库来做到这一点?

<Customer>
 <CustInfo>
  <CustAddr>
   <FullName>MY PRIMARY NAME</FullName>
   <Addr1>PRIMARY ADDRESS1</Addr1>
   <Addr2>PRIMARY ADDRESS2</Addr2>
   <Addr3>PRIMARY ADDRESS3</Addr3>
   <Addr4></Addr4>
   <Addr5></Addr5>
   <AddrCode>PRIMARY</AddrCode>
  </CustAddr>
  <CustAddr>
   <FullName>MY ALTERNATE ADDRESS LINE 1</FullName>
   <Addr1>TEST ALT ADDRESS LINE1</Addr1>
   <Addr2>TEST ALT ADDRESS LINE2</Addr2>
   <Addr3>TEST ALT ADDRESS LINE3</Addr3>
   <Addr4></Addr4>
   <Addr5></Addr5>
   <AddrCode>ALTERNATE</AddrCode>
  </CustAddr>
 </CustInfo>
</Customer>

1 个答案:

答案 0 :(得分:0)

尝试遵循xml linq。我用正则表达式来获取地址。需要避免将AddrCode作为地址的一部分。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            string xml = File.ReadAllText(FILENAME);

            //use parse to take string returned from request
            XDocument doc = XDocument.Parse(xml);

            KeyValuePair<string, List<string>> results = doc.Descendants("CustAddr").Where(x => (string)x.Element("AddrCode") == "PRIMARY")
                .Select(x => new KeyValuePair<string, List<string>>((string)x.Element("FullName"), x.Elements().Where(y => Regex.IsMatch(y.Name.LocalName, @"Addr\d")).Select(y => (string)y).ToList())).FirstOrDefault(); 

        }
    }
}