将Xml Post Data解析为Dictionnary

时间:2017-03-21 06:12:34

标签: .net regex dictionary xml-parsing

我有一些SaleForce发送到我的网络服务的帖子

 [Route("SendPixel")]
 [HttpPost]
 [HttpGet]
 public string SendPixel(HttpRequestMessage request)
 {

      var content = Request.Content.ReadAsStringAsync().Result;
      //parse
  }

内容:

   <?xml version="1.0" encoding="UTF-8"?>
<soapenv:Body>
    <Notification>
     <sObject xsi:type="sf:Lead" xmlns:sf="urn:sobject.enterprise.soap.sforce.com">
         <sf:Email>wow@vova.wow</sf:Email>
         <sf:Phone>1237556969</sf:Phone>
        </sObject>
       </Notification>
      </notifications>
 </soapenv:Body>
</soapenv:Envelope>

我需要解析它  **

  

字典QueryStringData = new Dictionary();

**

该密钥将为“电子邮件”,值为“wow@vova.wow”

QueryStringData[Email][wow@vova.wow]
QueryStringData[Phone][1237556969]

我该怎么办?正则表达还是有另一种方式?

在xml中,您可以看到在我需要的密钥之前总是有<sf:,然后是值。

有没有办法像这样解析为词典?

<sf:Phone>1237556969</sf:Phone> ==> <sf:KEY>VALUE</sf:KEY>

1 个答案:

答案 0 :(得分:0)

这将完成当前格式的工作。

     Dictionary<string, string> _dictionary = new Dictionary<string, string>();
                        string key = "";
                        string value = "";
              string xmlData = Request.Content.ReadAsStringAsync().Result;
using (XmlReader readerTest = XmlReader.Create(new StringReader(xmlData)))
                    {
                        while (readerTest.Read())
                        {
                            if (readerTest.LocalName.Contains("Notification"))
                            {
                                try
                                {
                                    readerTest.MoveToContent();
                                    while (readerTest.Read())
                                    {
                                        if (readerTest.Name.Contains("sf"))
                                        {
                                            key = readerTest.LocalName;
                                            value = readerTest.ReadElementContentAsString();
                                            if (!string.IsNullOrEmpty(key))
                                            {
                                                _dictionary.Add(key, value);
                                            }


                                        }

                                    }
                                    break;
                                }
                                catch (Exception ex) { }
                            }
                        }
                        readerTest.Close();
                    }