如何返回表示网站地址的内部文本
本文关键字:地址 网站 内部 文本 表示 何返回 返回 | 更新日期: 2023-09-27 18:23:57
我对XML编码还很陌生,需要一些LINQ查询的帮助,这将允许我返回字符串,该字符串表示XML响应中的站点地址,如下图所示:
<Response>
<Status>OK</Status>
<CustomFields>
<CustomField>
<ID>1</ID>
<Name>Date Field</Name>
<Date>2010-10-11T00:00:00</Date>
</CustomField>
<CustomField>
<ID>2</ID>
<Name>Number Field</Name>
<Number>123</Number>
</CustomField>
<CustomField>
<ID>3</ID>
<Name>Delivery Address</Name>
<Text>176 Monash Avenue, Nedlands</Text>
</CustomField>
</CustomFields>
</Response>
XML是对我们基于云的作业成本计算系统的RESTGET查询的响应。到目前为止,我的代码如下所示。这实际上可以返回一个列表,然后我必须遍历列表,直到找到站点地址(Delivery Address)。我希望有一种方法可以更简单地做到这一点,直接访问包含"交货地址"的元素?
List<CustomField> customfield = new List<CustomField>();
string endpoint = "https://api.workflowmax.com/job.api/get/"+ jobnum + "/customfield?apiKey=" + API_Key + "&accountKey=" + Account_Key;
var client = new RestClient(endpoint: endpoint, method: HttpVerb.GET);
var json = client.MakeRequest();
string response = json;
//load the unparsed string into an XML document
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(response);
customfield =
xdoc.Root
.Descendants("CustomFields")
.Select(n =>
new CustomField
{
ID = (string)n.Element("ID"),
Name = (string)n.Element("Name"),
Text = (string)n.Element("Client").Element("ID"),
})
.ToList();
您可以使用XPath提取名称为Site Address
的CustomField
中的Text
值。
using System.Xml.Linq;
using System.Xml.XPath; // contains extension method XPathSelectElement
/* ... */
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(response);
string address = xdoc
.XPathSelectElement("Response/CustomFields/CustomField[Name = 'Delivery Address']/Text")
.Value;
以下是W3C的XPath教程。