当我运行<!-- This list contains names/words with specific casing - and specific to english only -->
时,将在新目的地中删除。
有没有办法阻止它发生。我事件尝试XDocument.Root
同样的事情发生了。
Ps:我知道方法不在课内:)。
<!-- This list contains names/words with specific casing - and specific to english only -->
<ignore_list>
<name>A.M.</name>
<name>Aaron</name>
<name>Abbie</name>
<name>Abi</name>
<name>Abigail</name>
<name>Abolfazl</name>
<name>Adam</name>
</ignore_list>
private static void EnGBNamesEtc()
{
var listNames = new List<string>(){"some", "names");
var xele = XElement.Load(@"C:\Users\ivandro\Source\subtitleedit\Dictionaries\en_GB_names_etc.xml");
var names = listNames.Except(xele.Elements("name").Select(n => n.Value)).ToList();
foreach (var newName in names)
{
xele.Add(new XElement("name", newName));
}
SaveToNewXml(xele, @"D:\Backup\en_GB_names_etc1.xml");
}
private static void SaveToNewXml(XElement xelem, string dest)
{
XmlWriterSettings xws = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true };
var ordered = xelem.Elements("name").OrderBy(element => element.Value).ToList();
using (XmlWriter xw = XmlWriter.Create(dest, xws))
{
xelem.ReplaceAll(ordered);
xelem.Save(xw);
}
}
答案 0 :(得分:2)
这可能是因为您使用XElement
只能表示单个节点(当您有两个&#34; root&#34;节点,<ignore_list>
时评论节点)。例如,使用XDocument
代替XElement
来保留评论节点(我尝试对原始代码进行最小的更改):
private static async void EnGBNamesEtc()
{
var listNames = new List<string>(){"some", "names");
var xdoc = XDocument.Load(@"C:\Users\ivandro\Source\subtitleedit\Dictionaries\en_GB_names_etc.xml");
var names = listNames.Except(xdoc.Root.Elements("name").Select(n => n.Value)).ToList();
foreach (var newName in names)
{
xdoc.Root.Add(new XElement("name", newName));
}
SaveToNewXml(xdoc, @"D:\Backup\en_GB_names_etc1.xml");
}
private static void SaveToNewXml(XDocument xdoc, string dest)
{
XmlWriterSettings xws = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true };
var ordered = xdoc.Root.Elements("name").OrderBy(element => element.Value).ToList();
using (XmlWriter xw = XmlWriter.Create(dest, xws))
{
xdoc.Root.ReplaceAll(ordered);
xdoc.Save(xw);
}
}