简体   繁体   English

如何在 C# 中更新 XML 文档的特定子节点值

[英]How to Update a Specific Child Node Value of XML Document in C#

I have a method like below where I am getting all the parameter value from another method, where我有一个像下面这样的方法,我从另一个方法中获取所有参数值,其中

    type = DeviceParameters
    sourceXml = <?xml version="1.0" encoding="utf-16"?>
            <ProductCode>
              <DeviceParameters>
                <P65>True</P65>
                <HWVersion>1</HWVersion>
                <Test>Test</Test>
                <Test>hello</Test>
              </DeviceParameters>
              <FirmwareGates>
                <Firmware>120.0.23</Firmware>
              </FirmwareGates>
              <ModemIncludeList>
                <Modem>Test</Modem>
                <ModemFirmware>2</ModemFirmware>
              </ModemIncludeList>
            </ProductCode>
    oldParameterName= Test
    oldParameterValue= hello
    newParameterName = Test
    parameterValue = hello123

I am trying to update the value for the node <Test>hello</Test> to <Test>hello123</Test>我正在尝试将节点<Test>hello</Test>的值更新为<Test>hello123</Test>

EDIT: I have tried to Removed the parameter and readd with the new value but it seems like more difficult.编辑:我试图删除参数并使用新值读取,但似乎更困难。 Is there any way to update the value?有什么方法可以更新值吗?

private string EditParameter(TesterParameterCodeType type, string sourceXml, string oldParameterName, string oldParameterValue, string newParameterName, string parameterValue, int index)
            {
XDocument doc = XDocument.Parse(sourceXml); // or XDocument.Parse(string)
            doc.Root.Descendants().Where(e => e.Name == oldParameterName && e.Value == oldParameterValue).Remove();           

                var stringWriter = new StringWriter();
                doc.Save(stringWriter);
                return stringWriter.ToString();
        }

To make InnerText property available in auto complete just change your for using the correct type of your node variable要使 InnerText 属性在自动完成中可用,只需更改您使用的节点变量的正确类型

foreach (XmlElement node in parameterNode)

To remove the node in your if just select the parent of you node and remove the current node from the parent:要删除节点中的节点,只需选择节点的父节点并从父节点中删除当前节点:

if(node.InnerText == parameterValue)
{
    var parentNode = node.ParentNode;
    parentNode.RemoveChild(node);
}

You can see an example of your full conde in this link:您可以在此链接中查看完整 conde 的示例:

https://dotnetfiddle.net/2Fe2ss https://dotnetfiddle.net/2Fe2ss

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM