Web Api上的xmlDocument查找最后一个属性

时间:2014-04-15 19:32:15

标签: c# xml asp.net-web-api

这是用于获取xml文档的最后一个节点的模板代码

var highestAccount = (
from Accounts in xmlDocument.Elements("catalog").Elements("account")
orderby Accounts.Attribute("id").Value descending
select Accounts).Take(1);

   string highestId = highestAccount.Attributes("id").First().Value;

   string newId = "bk" + (Convert.ToInt32(highestId.Substring(2)) + 1).ToString(); 

但它不起作用。调试器无法捕获它,因为它是一个webapi,代码启动时没有异常。

这是XML

<?xml version="1.0" encoding="utf-8"?>
      <catalog>
  <account id="1">
    <username>admin</username>
    <password>admin</password>
    <department>Admin</department>
  </account>
  <account id="bk">
    <username>sds</username>
    <password>dsds</password>
    <department>ds</department>
  </account>
</catalog>

它表示存在内部服务错误,但是当我说

string newId = "123" 

它会像魅力一样工作。请帮忙

1 个答案:

答案 0 :(得分:1)

您的代码可能会抛出FormatException。您从选择中获得的第一个ID是&#34; bk&#34;。然后从位置2开始Substring,这是一个空字符串。当给定空字符串时,Convert.ToInt32将抛出异常。

如果您有一个填充的ID列表,其格式为&#34; bkNN&#34;,那么您将遇到OrderBy降序问题......如下列表:

var idList = new List<String> {"bk1", "bk2", "bk3", "bk4", "bk5", 
    "bk6", "bk7", "bk8", "bk9", "bk10", "bk11"};

将按顺序降序为&#34; bk9&#34;,&#34; bk8&#34;,&#34; bk7&#34; ......&#34; bk2&#34;,&#34; bk11&#34;,&#34; bk10&#34;,&#34; bk1&#34;。

要获得您正在寻找的行为,请尝试以下方法:

string newId = "bk" + 
    (idList.Where(id => id.StartsWith("bk") && id.Length > 2)
           .Select(id => Convert.ToInt32(id.Substring(2)))
           .OrderByDescending(id => id)
           .FirstOrDefault() + 1);