XDocument正在删除文档注释

本文关键字:文档 注释 删除 XDocument | 更新日期: 2023-09-27 18:07:33

当我运行<!-- 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);
    }
}

XDocument正在删除文档注释

这可能是因为您使用的XElement仅能够表示单个节点(当您有两个"根"节点,<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);
    }
}