[英]List from nested Values XML Linq C#
我从 API 请求一些数据作为 XML。 首先获取 id,然后将 id 发布到第二个端点以获取相关数据。 我遇到的问题是提取 id 并将它们放入一个列表中,例如List<string>() { "idxxxx", "idxxxx", "idxxxx", "idxxxx" }
用于 POST 请求正文。 GET 响应 (xmlStringResponse) 看起来像这样
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><TaxeringsenhetsreferensResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:lmfault="http://namespace.lantmateriet.se/distribution/produkter/fault/v1" xmlns="http://namespace.lantmateriet.se/distribution/produkter/taxering/v2" xmlns:gml="http://www.opengis.net/gml/3.2"><Taxeringsenhetsreferens><id>553508-5</id><typ>Lantbruksenhet</typ></Taxeringsenhetsreferens><Taxeringsenhetsreferens><id>553511-5</id><typ>Specialenhet</typ></Taxeringsenhetsreferens><Taxeringsenhetsreferens><id>559405-5</id><typ>Industrienhet</typ></Taxeringsenhetsreferens><Taxeringsenhetsreferens><id>710531-4</id><typ>Industrienhet</typ></Taxeringsenhetsreferens></TaxeringsenhetsreferensResponse>
此时的代码看起来像这样,并且 idListXml 一直为空。 我在这里做错了,无法弄清楚..
XElement xmlTree = XElement.Parse(xmlStringResponse);
var idList = xmlTree.Descendants("Taxeringsenhetsreferens")
.Select(x => (string)x.Element("id"))
.ToList();
XElement requestBody = new XElement(ns + "IdRequest", idList.Select(l => new XElement(ns + "id", l)));
感谢您的时间!
你的代码很好,你可以添加XNamespace ,试试下面的代码:
XElement xmlTree = XElement.Parse(xmlStringResponse);
XNamespace ns = "http://namespace.lantmateriet.se/distribution/produkter/taxering/v2";
var idList = xmlTree.Descendants(ns + "Taxeringsenhetsreferens")
.Select(x => x.Element(ns + "id").Value)
.ToList();
我希望这会帮助您获得预期的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.