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

如何在XML子节点中添加多组属性及对应值?含添加Rule元素需求

解决XML中添加Rule子元素及多属性的问题

首先你提供的原XML存在语法错误,比如根标签<GlobalAppSettings未闭合、第一个<NameSpace>标签缺少闭合标记,先修正为合法的XML结构:

<GlobalAppSettings>
  <NameSpace name="retail" />
  <NameSpace name="APEService" inheritsFrom="retail">
    <Rules>
      <Rule namespace="retail" queues="Default" scanInterval="10000" threads="2" />
      <Rule namespace="retail" queues="DLS" scanInterval="9000" threads="1" />
    </Rules>
  </NameSpace>
</GlobalAppSettings>

手动添加Rule子元素及多属性

要在APEService的<Rules>节点下新增Rule元素,只需在现有Rule节点后插入新的自闭合标签,并按需定义属性键值对即可。比如新增一个针对Priority队列的Rule:

<GlobalAppSettings>
  <NameSpace name="retail" />
  <NameSpace name="APEService" inheritsFrom="retail">
    <Rules>
      <Rule namespace="retail" queues="Default" scanInterval="10000" threads="2" />
      <Rule namespace="retail" queues="DLS" scanInterval="9000" threads="1" />
      <!-- 新增的Rule元素,包含多组自定义属性 -->
      <Rule namespace="retail" queues="Priority" scanInterval="5000" threads="3" enabled="true" />
    </Rules>
  </NameSpace>
</GlobalAppSettings>

添加时注意这几点:

  • 新元素必须放在父节点<Rules>的起始标签和结束标签之间
  • 属性格式为属性名="属性值",多个属性用空格分隔,顺序不影响解析
  • 所有属性值必须用双引号或单引号包裹,不能遗漏
  • 自闭合元素要以/>结尾,确保XML结构合法

代码方式动态添加(以C#为例)

如果需要通过代码批量或动态添加,可使用XmlDocument类操作:

XmlDocument doc = new XmlDocument();
doc.Load("你的配置文件路径.xml");

// 定位到目标Rules节点
XmlNode rulesNode = doc.SelectSingleNode("//NameSpace[@name='APEService']/Rules");

// 创建新的Rule元素
XmlElement newRule = doc.CreateElement("Rule");
// 依次添加多组属性
newRule.SetAttribute("namespace", "retail");
newRule.SetAttribute("queues", "Priority");
newRule.SetAttribute("scanInterval", "5000");
newRule.SetAttribute("threads", "3");
newRule.SetAttribute("enabled", "true");

// 将新元素追加到Rules节点下
rulesNode.AppendChild(newRule);

// 保存修改后的XML
doc.Save("你的配置文件路径.xml");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 17:07:31