【发布时间】:2018-04-22 07:15:55
【问题描述】:
这是一个示例 xml
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
<book id="bk102">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society.</description>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>In post-apocalypse England, the mysterious
agent known only as Oberon helps to create a new life
for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>
</catalog>
如何检查节点<book>中属性id的值是否按升序排列,同时以最简单的方式查找其中是否存在重复值。
我做了
static void Main(string[] args)
{
XDocument myfile = XDocument.Parse(File.ReadAllText(@"D:\sample_xml.xml"));
var check = myfile.Descendants("book").Select(a => a.Attribute("id").Value.Substring(2)).ToArray();
if (IsSortedAscending(check))
{
Console.WriteLine("Sorted in Ascending order");
}
else
{
Console.WriteLine("Check Sequence");
}
Console.ReadLine();
}
public static bool IsSortedAscending(string[] arr)
{
for (int i = arr.Length - 2; i >= 0; i--)
{
if (arr[i].CompareTo(arr[i + 1]) > 0)
{
return false;
}
}
return true;
}
但它不考虑重复值...我该怎么做?
另外,是否可以在属性 id 中找到缺失值(如果有),例如如果有 bk109 而下一个是 bk112 则程序将显示 bk110 和 bk111 缺失。
【问题讨论】:
-
使用 XML 反序列化将 xml 数据加载到对象,然后使用 LINQ。 stackoverflow.com/questions/18340427/…
-
@RudreshaParameshappa:为什么要反序列化? LINQ to XML 使这变得微不足道。
-
@DaisyShipton 哦,是的,谢谢,我忘了..