不要求任何人为我编写此解决方案的代码-只是寻找最佳方法的指导。我正在使用后面的C#代码在VS2015中处理.aspx文件。
我发现了无数线程来解释如何对XML文件中的节点进行排序。但是,根据通用的子节点属性,我没有找到关于如何对具有相同结构的多个XML文件进行排序的任何线程。
我的情况:我有一个包含数百个XML文件的目录,简单地命名为0001.xml到6400.xml。每个XML文件具有相同的结构。我想根据子节点的属性对文件(而不是节点)进行排序。
每个XML文件都有一个“项目”父节点,还有一个子节点“年”,“语言”和“作者”等。例如:
<item id="0001">
<year>2011</year>
<language id="English" />
<author sortby="Smith">John F. Smith</author>
<content></content>
</item>
如果不是要按照0001至6400的顺序列出文件,而是要根据item / author节点的@sortby属性按字母顺序列出它们,我该怎么做?
我曾经想到的一个想法是创建一个临时XML文件,该文件收集每个XML文件所需的信息。然后,我可以对临时XML文件进行排序,然后遍历节点以正确的顺序显示文件。像这样
XDocument tempXML = new XDocument();
// add parent node of <items>
string[] items = Directory.GetFiles(directory)
foreach (string item in items)
{
// add child node of <item> with attributes "filename", "year", "language", and "author"
}
// then sort the XML nodes according to attributes
这有意义吗?有更聪明的方法吗?
我们可以使用以下代码显示使用LINQ to Xml排序的xml文件:
var xmlsWithFileName = Directory.GetFiles(directory)
.Select(fileName => new { fileName, xml = XDocument.Parse(File.ReadAllText(fileName)) })
.OrderBy(tuple => tuple.xml.Element("item").Element("author").Attribute("sortby").Value);
xmlsWithFileName的每个元素都将具有
假设在目标目录中有以下xml文件:
<item id="0001">
<year>2011</year>
<language id="English" />
<author sortby="Smith">John F.Smith</author>
<content></content>
</item>
<item id="0002">
<year>2012</year>
<language id="Portuguese" />
<author sortby="Monteiro">Alberto Monteiro</author>
<content></content>
</item>
您可以使用此代码进行测试
public static void ShowXmlOrderedBySortByAttribute(string directory)
{
var xmlsWithFileName = Directory.GetFiles(directory)
.Select(fileName => new { fileName, xml = XDocument.Parse(File.ReadAllText(fileName)) })
.OrderBy(tuple => tuple.xml.Element("item").Element("author").Attribute("sortby").Value);
foreach (var xml in xmlsWithFileName)
{
Console.WriteLine($"Filename: {xml.fileName}{Environment.NewLine}Xml content:{Environment.NewLine}");
Console.WriteLine(xml.xml.ToString());
Console.WriteLine("================");
}
}
这段代码的输出是:
Filename: c:\temp\teste\0002.xml
Xml content:
<item id="0002">
<year>2012</year>
<language id="Portuguese" />
<author sortby="Monteiro">Alberto Monteiro</author>
<content></content>
</item>
================
Filename: c:\temp\teste\0001.xml
Xml content:
<item id="0001">
<year>2011</year>
<language id="English" />
<author sortby="Smith">John F.Smith</author>
<content></content>
</item>
================
如您所见,XML 0002.xml出现在第一位置,然后是0001.xml。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句