You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中比较XmlDocument的XmlNode并判断字体节点是否已存在?

嘿,我来帮你搞定这两个XmlDocument相关的问题~

一、检查XmlDocument中是否存在指定的font节点

要判断目标font节点是否已存在,我们可以利用XPath查询来快速定位,具体可以根据你的匹配规则选择不同的查询方式:

1. 根据role属性判断(最常见场景)

如果你的font节点是通过role唯一标识的(比如示例里的console、default、titles),可以直接用SelectSingleNode查询对应role的节点:

XmlDocument doc = new XmlDocument();
doc.Load("你的配置文件路径.xml"); // 也可以用doc.LoadXml()加载字符串形式的XML

// 假设要检查role为"custom"的font节点是否存在
string targetRole = "custom";
XmlNode existingFont = doc.SelectSingleNode($"//font[@role='{targetRole}']");

if (existingFont != null)
{
    Console.WriteLine("该role对应的font节点已经存在啦!");
}
else
{
    Console.WriteLine("没有找到匹配的节点,可以添加新的font配置~");
}

2. 根据字体名(fname)和字号(size)判断

如果需要判断是否有完全相同的字体配置(不考虑role),可以组合查询子节点的内容:

string targetFontName = "Arial";
int targetFontSize = 12;

// 用XPath匹配fname和size都一致的font节点
XmlNode duplicateFont = doc.SelectSingleNode($"//font[fname='{targetFontName}' and size='{targetFontSize}']");

if (duplicateFont != null)
{
    Console.WriteLine("已经存在相同的字体配置啦!");
}
二、在C#中比较两个XmlNode

比较两个XmlNode是否相等,有两种常用方式,你可以根据需求选择:

1. 直接比较节点的XML字符串(简单快捷)

利用OuterXml属性获取节点的完整XML字符串表示,直接对比字符串即可:

// 假设node1和node2是你要比较的两个XmlNode
bool isEqual = node1.OuterXml.Equals(node2.OuterXml, StringComparison.OrdinalIgnoreCase);
  • 优点:代码简单,无需额外逻辑
  • 注意:如果需要区分大小写(比如字体名的大小写),可以去掉StringComparison.OrdinalIgnoreCase参数

2. 递归手动比较(灵活自定义规则)

如果需要更精细的控制(比如忽略某些属性、不考虑子节点顺序等),可以写一个递归方法逐个比较节点的细节:

public static bool AreXmlNodesEqual(XmlNode nodeA, XmlNode nodeB)
{
    // 先检查节点类型是否一致
    if (nodeA.NodeType != nodeB.NodeType)
        return false;

    // 检查节点名称
    if (nodeA.Name != nodeB.Name)
        return false;

    // 比较属性
    if (nodeA.Attributes != null && nodeB.Attributes != null)
    {
        if (nodeA.Attributes.Count != nodeB.Attributes.Count)
            return false;

        foreach (XmlAttribute attr in nodeA.Attributes)
        {
            XmlAttribute otherAttr = nodeB.Attributes[attr.Name];
            if (otherAttr == null || attr.Value != otherAttr.Value)
                return false;
        }
    }
    else if (nodeA.Attributes != null || nodeB.Attributes != null)
    {
        // 一个有属性,一个没有,直接不相等
        return false;
    }

    // 比较子节点数量
    if (nodeA.ChildNodes.Count != nodeB.ChildNodes.Count)
        return false;

    // 递归比较每个子节点
    for (int i = 0; i < nodeA.ChildNodes.Count; i++)
    {
        if (!AreXmlNodesEqual(nodeA.ChildNodes[i], nodeB.ChildNodes[i]))
            return false;
    }

    // 比较节点的文本内容
    if (nodeA.InnerText != nodeB.InnerText)
        return false;

    return true;
}

调用时直接传入两个节点即可:

bool nodesMatch = AreXmlNodesEqual(node1, node2);

内容的提问来源于stack exchange,提问作者Mullai Nathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:17:01