c# - 将 XML 属性读入列表

标签 c# xml list httpwebrequest

我是 XML 的新手,无法从 HttpWebResponse 读取我的 XML 响应。

这是回复:

<RESPONSE version="1.2">
 <RESULTS>
  <AN an_type="C" 
  an_id="783hdryfdg56a2" 
   an_num="1" 
    an_status="100" />
  <RESULTS>
</RESPONSE>

我希望提取 an_id 值并将其保存到列表中。开始这样做但似乎得到一个 for xmlnodelist 作为一个 int 但它认为 nodes["an_id"] 是一个字符串

List<int> IDs = new List<int>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(returnValue);
XmlNodeList nodes = doc.SelectNodes("SEARCH_RESULTS/LOAN");
LoanIDs.Add(Convert.ToInt32(nodes["an_id"].InnerText));

这也是他们将 an_id 添加到列表后的一种方式。 foreach 列表中的项目将其用作新 xml 的参数,如下所示:

<INPUT>
        <LOGIN API_ID=""cat"" API_PASSWORD=""dog"" />
    <REQUEST>
         <AN an_id=""@anID"" />  
         <AN an_id=""@anID"" />
        ....foreach one in list it adds a new node with the value
    </REQUEST>
</INPUT>

最佳答案

xml 是带有 XML 代码的字符串:

var ids = XDocument.Parse(xml).
    Descendants("AN").
    Select(e => (string)e.Attribute("an_id")).
    ToList();

但是,从您的样本来看,该属性似乎并不总是一个整数。 您确定要转换吗?根据您的最新评论,我将属性的转换更改为 (string)。

当您想重用列表时,current 是包含您要添加的列表的父元素:

current.Add(ids.Select(i => new XElement("AN", new XAttribute("an_id", i))));

关于c# - 将 XML 属性读入列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13979454/

相关文章:

c# - 在 DNX 项目中,我如何定位 Xamarin Android?

c# - 私有(private)类成员中关键字 'this' 的正确用法是什么?

c# - 在 C# 中将十进制数组转换为字节数组,反之亦然

c# - 在属性网格上显示数据

xml - 如何获取所有使用的命名空间的列表?

c# - 与 C# 中的嵌套表达式树作斗争

xml - 需要使用 XSLT 从 XML 输出文本节点的帮助

python - 递增列表索引 if 条件

arrays - 如何在golang中使用for循环将值存储在结构中

java - 常规/katalon : Validate sequence of list