编辑:我认为原因是因为“UniversalShipment”xmlns。有一个链接,但我删除它的机密性。我无法通过该节点。帮助我在ChooseSingleNode时遇到错误
这是我的XML。
<UniversalInterchange xmlns="" version="1.0">
<Header>
<SenderID>1</SenderID>
<RecipientID>2</RecipientID>
</Header>
<Body>
<UniversalShipment xmlns="" version="1.1">
<Shipment>
<CustomizedFieldCollection>
<CustomizedField>
<Key>Documents Checked</Key>
<DataType>Boolean</DataType>
<Value>false</Value>
</CustomizedField>
<CustomizedField>
<Key>Date Completed</Key>
<DataType>DateTime</DataType>
<Value></Value>
</CustomizedField>
</CustomizedFieldCollection>
</Shipment>
</UniversalShipment>
</Body>
</UniversalInterchange>
当我得到单节点时,我收到null。但是,当我尝试“身体”只在单个节点它添加到底部。如果我试图将其添加到UniversalShipment“Body/UniversalShipment”,它会遇到错误。
XmlDocument doc=new XmlDocument();
doc.Load("sample.xml");
XmlNode customizedNode = doc.CreateElement("CustomizedField");
XmlNode keyNode = doc.CreateElement("Key");
XmlNode dataNode = doc.CreateElement("DataType");
XmlNode valueNode = doc.CreateElement("Value");
keyNode.InnerText = "hi";
dataNode.InnerText = "hello";
valueNode.InnerText = "bye";
customizedNode.AppendChild(keyNode);
customizedNode.AppendChild(dataNode);
customizedNode.AppendChild(valueNode);
doc.DocumentElement.SelectSingleNode("Body/UniversalShipment/Shipment/CustomizedFieldCollection").AppendChild(customizedNode);
doc.Save("sample.xml");
从根开始表达或“/”文档元素是这样的:UniversalInterchange/Body/UniversalShipment/Shipment/CustomizedFieldCollection。我没有尝试过,但它应该工作。 – seesharpconcepts
@seesharpconcepts“UniversalInterchange/Body/UniversalShipment/Shipment/CustomizedFieldCollection”我仍然遇到错误。我认为这是因为xmlns。有一个链接提供,但我删除它。我无法显示给你的链接。 – Reynan
上面的Xpath在没有声明名称空间的情况下工作。初始化XmlNamespaceManager并将其作为参数传递给Select方法。链接到msdn:https://msdn.microsoft.com/en-us/library/h0hw012b(v=vs.110).aspx – seesharpconcepts