尝试更改 XML 节点但没有成功

Trying to change a XML node with no success

我正在尝试更改以下 .xml 文件中 model 属性的值。

<MTConnectDevices xmlns="urn:mtconnect.org:MTConnectDevices:1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:mtconnect.org:MTConnectDevices:1.1 http://www.mtconnect.org/schemas/MTConnectDevices_1.1.xsd">
  <Header version="1.1" sender="Company MTConnect Instance" creationTime="2010-08-26T19:00:47-07:00" instanceId="2" bufferSize="131072" />
  <Devices>
    <Device name="XX" iso841Class="1" uuid="000" id="id1001">
      <Description manufacturer="name" serialNumber="Serial Number" model="UNDEFINED">
      </Description>

这是我试过的方法,但它没有用,因为它没有改变 model 的值。

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(mypath);
        var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
        nsmgr.AddNamespace("ns", xmlDoc.DocumentElement.NamespaceURI);
        var node = xmlDoc.SelectSingleNode("/ns:MTConnectDevices/ns:Header/ns:Devices/ns:Device/ns:Description", nsmgr);
        node.Attributes["model"].Value = "changed";
        xmlDoc.Save(mypath);

任何人都可以帮助我并告诉我如何解决这个问题吗?

您的 xml 包含名称空间,因此您必须在检索节点时使用它们。

可以这样做:

var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ns", xmlDoc.DocumentElement.NamespaceURI);
var node = xmlDoc.SelectSingleNode("/ns:MTConnectDevices/ns:Devices/ns:Device/ns:Description", nsmgr);