简体   繁体   English

将XML属性读入列表

[英]Reading XML Attributes into a List

I'm new to XML and am having trouble reading my XML response back from a HttpWebResponse. 我是XML新手,无法从HttpWebResponse读回我的XML响应。

Here is the response back: 以下是回复:

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

I'm looking to extract out the an_id value and save it to a list. 我想要提取出an_id值并将其保存到列表中。 Started doing this but seems to get an for xmlnodelist as an int but it thinks nodes["an_id"] is a string 开始这样做但似乎得到一个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));

Also is their a way to once the an_id's are added to a list. 一旦将an_id添加到列表中,它们也是一种方法。 foreach item in the list use it as aparameter for a new xml like this: 列表中的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>

With xml being your string with the XML code: 使用xml作为XML代码的字符串:

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

However, from your sample it didn't seem that the attribute is always an integer. 但是,从您的示例中,似乎该属性始终不是整数。 Are you sure about your conversion? 你确定要转换吗? I changed the cast of the attribute to (string) given your latest comment. 鉴于您的最新评论,我将属性的强制转换为(字符串)。

When you want to reuse the list, with current being the parent element containing the ones you want to add: 如果要重用列表,则current是包含要添加的父元素:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM