这是一个示例xml。如果要在某种意义上添加新字体,则在添加到首选项之前,将所有现有字体与新字体进行比较。
在XmlDocument的情况下,如何检查节点(字体)是否已经存在?

<preferences>
  <font role="console">
    <size>9</size>
    <fname>Courier</fname>
  </font>
  <font role="default">
    <fname>Times New Roman</fname>
    <size>14</size>
  </font>
  <font role="titles">
    <size>10</size>
    <fname>Helvetica</fname>
  </font>
</preferences>

最佳答案

一种方法是创建几个类来表示XML文档并实现IEquatable<T> Interface

https://dotnetfiddle.net/QZFwDy

XML类

[XmlRoot(ElementName = "font")]
public class Font : IEquatable<Font>
{
    [XmlElement(ElementName = "size")]
    public string Size { get; set; }
    [XmlElement(ElementName = "fname")]
    public string Fname { get; set; }
    [XmlAttribute(AttributeName = "role")]
    public string Role { get; set; }

    public bool Equals(Font font)
    {
        if (font == null) return false;

        return (Size == font.Size) && (Fname == font.Fname) && (Role == font.Role);
    }
}

[XmlRoot(ElementName = "preferences")]
public class Preferences
{
    [XmlElement(ElementName = "font")]
    public List<Font> Font { get; set; }
}


然后,使用Preferences类反序列化XML。反序列化文档后,利用List<T>.Contains(T item)方法查看字体节点是否存在。 .Contains方法将在Equals类中调用Font的实现。

演示代码

static void Main(string[] args)
{
    Preferences preferences = null;
    var xmlString = Data.XML;

    using (var stream = new StringReader(xmlString))
    {
        var serializer = new XmlSerializer(typeof(Preferences));
        preferences = (Preferences)serializer.Deserialize(stream);
    }

    var node0 = new Font()
    {
        Fname = "New One",
        Role = "console",
        Size = "12"
    };

    var node1 = new Font()
    {
        Fname = "Helvetica",
        Role = "titles",
        Size = "10"
    };

    if (preferences.Font.Contains(node0))
    {
        // Not expecting to enter here
        Console.WriteLine($"'{nameof(node0)}' is already present");
    }

    if (preferences.Font.Contains(node1))
    {
        Console.WriteLine($"'{nameof(node1)}' is already present");
    }
}

09-25 18:11