You need to enable JavaScript to run this app. C#基于XmlDocument获取指定节点后所有同级节点并修改Height值
优惠活动
大模型
产品
解决方案
定价
更多

C#基于XmlDocument获取指定节点后所有同级节点并修改Height值

C# XmlDocument 实现指定同级节点获取与Height更新

核心实现逻辑

给定XML中所有Textbox、Tablix均为的直接子节点,实现步骤为:定位锚点节点 → 从锚点起始遍历同级节点并筛选指定类型 → 批量更新Height值。

分步实现代码

  • 第一步:加载XML并定位锚点节点
// 初始化XmlDocument实例
XmlDocument xmlDoc = new XmlDocument();
// 加载XML内容,可替换为xmlDoc.LoadXml("XML字符串"直接加载内存中的XML
xmlDoc.Load("你的XML文件路径");

// 定位Name属性为TextboxSearchInjectionEnd的锚点节点
XmlNode anchorNode = xmlDoc.SelectSingleNode("//Report/Textbox[@Name='TextboxSearchInjectionEnd']");
if (anchorNode == null)
{
    throw new InvalidOperationException("未找到指定的锚点节点");
}
  • 第二步:获取从锚点开始的目标节点列表
    列表包含锚点节点自身及后续所有同级Textbox、Tablix节点,自动排除锚点之前的所有同级节点:
// 获取锚点的父节点(即<Report>节点)
XmlNode reportNode = anchorNode.ParentNode;
// 计算锚点节点在父节点子集合中的索引
int anchorIndex = reportNode.ChildNodes.IndexOf(anchorNode);
List<XmlNode> targetNodes = new List<XmlNode>();

// 从锚点索引开始向后遍历
for (int i = anchorIndex; i < reportNode.ChildNodes.Count; i++)
{
    XmlNode currentNode = reportNode.ChildNodes[i];
    // 仅保留Textbox、Tablix类型的节点
    if (currentNode.Name == "Textbox" || currentNode.Name == "Tablix")
    {
        targetNodes.Add(currentNode);
    }
}
  • 第三步:批量更新节点Height值
    注意:若仅需更新已存在Height子节点的元素,可在判断Height不存在时直接跳过,无需新建
// 替换为你需要设置的Height值
const decimal newHeight = 3;
foreach (XmlNode node in targetNodes)
{
    // 查找当前节点下的Height子节点
    XmlNode heightNode = node.SelectSingleNode("Height");
    if (heightNode == null)
    {
        // 不存在则自动创建Height节点,若不需要创建可直接continue跳过
        heightNode = xmlDoc.CreateElement("Height");
        node.AppendChild(heightNode);
    }
    // 更新Height值
    heightNode.InnerText = newHeight.ToString();
}

// 保存修改后的XML
xmlDoc.Save("修改后的XML存储路径");

常见调整说明

  • 若需排除锚点节点自身,只需将遍历起始索引改为anchorIndex + 1即可
  • 若XML中存在嵌套的Textbox、Tablix节点,可通过调整XPath规则或增加节点层级判断来过滤非直接子级节点

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.03 13:06:08