0

我的 MVC 应用程序的一部分是一个控制器操作方法,它将数据发布到 Web 服务并接收 XML 响应。我已经想出了如何将响应放入 XDocument,但现在我需要查看信息并获取一些节点值。我一直在研究,我能找到最接近的选择是使用 XPath。

我想知道这是否是最好的方法,或者您是否建议另一种方法。我正在使用的 XML 将类似于:

<HistoryResponse>
  <ResponseType>resultsList</ResponseType>
  <Matches>0</Matches>
  <SessionID>75803234r23df3de</SessionID>
  <RecStart>0</RecStart>
  <ClientCode></ClientCode>
  <Results></Results>
</HistoryResponse>

我需要通过,获取 Matches 和 SessionID 并将值放入变量中。

谢谢。

4

3 回答 3

1

您可以将您的 xml 转换为字典

var xDoc = XDocument.Parse(xmlstring); //XDocument.Load(fileName)
var dict = xDoc.Element("HistoryResponse")
               .Elements()
               .ToDictionary(e => e.Name.LocalName, e => e.Value);

并用作

string sessionID = dict["SessionID"];
于 2012-12-12T19:45:45.583 回答
0

Use LINQtoXML. (you need to import the namespace System.XML.Linq)

string filePath = Server.MapPath(@"../YourFileLocation/somexml.xml");

//you can load the XML from file/stream /string etc...

XElement elem = XElement.Load(filePath);
if (elem != null)
{
   string sessionId=elem.Element("SessionID").Value;
   string matches=elem.Element("Matches").Value;
}

If you are getting the XML in a string, you can load that to your XElement using Parse method.

string xml = "<HistoryResponse><Item>XML Item A</Item></HistoryResponse>";
XElement elem = XElement.Parse(xml);
于 2012-12-12T19:40:30.033 回答
0

That would definitely work with an XPath expression. Check out how to use XPath with XDocument? for info on how to do it.

于 2012-12-12T19:40:35.117 回答