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

如何修改XML中modification标签内的singleNssai属性值

问题解决:修改XML中modification标签name属性内的singleNssai值

需求

修改目标XML里modification标签的name属性字符串中@singleNssai='1-000002'部分,替换为@singleNssai='2-000001'。

原XML内容

<?xml version="1.0" encoding="UTF-8"?>
<spml:batchRequest xmlns:subscriber="urn:abc:names:prov:gw:SUBSCRIBER:3:0" xmlns:spml="urn:abc:names:prov:gw:SPML:2:0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" execution="synchronous" timestamp="true" processing="sequential" onError="exit_commit">
    <version>SUBSCRIBER_v30</version>
    <request xsi:type="spml:ModifyRequest" returnResultingObject="full">
        <version>SUBSCRIBER_v30</version>
        <objectclass>Subscriber</objectclass>
        <identifier>1234567890</identifier>
        <modification name="udm5gData/servingPlmnId[@plmnId='20201']/provisionedData/sessionManagementSubscriptionData[@singleNssai='1-000002']/dnnConfiguration[@dnnId='dj.nmdd']" operation="remove" scope="uniqueTypeMapping" xmlns:subscriber="urn:abc:names:prov:gw:SUBSCRIBER:3:0">
        </modification>
    </request>
</spml:batchRequest>

尝试的无效代码

XmlDataDocument doc = new XmlDataDocument();
doc.Load("D:\\soaptemp\\test.xml");

XmlNode singlenssais = 
doc.SelectSingleNode("//modification/name/@singleNssai");
if (singlenssais != null)
{
    singlenssais.Value = "2-000001"; // Set to new value.
}

问题原因

原代码的XPath表达式错误:@singleNssai并不是name属性的子属性,而是name属性值字符串里的一段内容。XPath无法直接选中字符串内的片段,必须先获取name属性的完整值,再通过字符串替换修改目标内容。

修正后的代码

XmlDataDocument doc = new XmlDataDocument();
doc.Load("D:\\soaptemp\\test.xml");

// 选中modification节点
XmlNode modificationNode = doc.SelectSingleNode("//modification");
if (modificationNode != null && modificationNode.Attributes["name"] != null)
{
    string originalNameValue = modificationNode.Attributes["name"].Value;
    // 替换目标字符串片段
    string updatedNameValue = originalNameValue.Replace("@singleNssai='1-000002'", "@singleNssai='2-000001'");
    // 把修改后的值赋值回属性
    modificationNode.Attributes["name"].Value = updatedNameValue;
    // 保存修改后的XML
    doc.Save("D:\\soaptemp\\test_modified.xml");
}

说明

  1. 先通过//modification选中目标节点
  2. 检查节点和name属性是否存在,避免空引用异常
  3. 获取name属性的原始值,用字符串替换修改指定片段
  4. 将修改后的值重新赋值给name属性
  5. 保存修改后的XML到指定路径

内容的提问来源于stack exchange,提问作者Dhananjaya D N

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:31:49