C# 如何修改xml内部属性

C# 如何修改xml内部属性,c#,xml,C#,Xml,我正在尝试编辑一个xml文件 XmlDocument myXmlDocument = new XmlDocument(); myXmlDocument.Load(@"C:\\Users\\Vahid\\Desktop\\HG\\HG\\HG\\singleM.kml"); XmlNode myNode = myXmlDocument.SelectSingleNode( "/kml/Document/Placemark/Point/coordinates"); myNode.Value =

我正在尝试编辑一个xml文件

XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.Load(@"C:\\Users\\Vahid\\Desktop\\HG\\HG\\HG\\singleM.kml");
XmlNode myNode = myXmlDocument.SelectSingleNode(
    "/kml/Document/Placemark/Point/coordinates");
myNode.Value = coordinates;
myXmlDocument.Save(@"C:\\Users\\Vahid\\Desktop\\HG\\HG\\HG\\singleM.kml");
这是我的xml(.kml)文件:


change.kml
0, 0,0
12
Xml名称空间:

XmlNamespaceManager ns = new XmlNamespaceManager(myXmlDocument.NameTable);
ns.AddNamespace("kml", "http://www.opengis.net/kml/2.2");
XmlNode myNode = myXmlDocument.SelectSingleNode("/kml:kml/kml:Document/kml:Placemark/kml:Point/kml:coordinates", ns);
myNode.InnerText = coordinates;
请注意,
“kml”
/
“kml:
这里没有什么特别之处-它也可以是:

XmlNamespaceManager ns = new XmlNamespaceManager(myXmlDocument.NameTable);
ns.AddNamespace("x", "http://www.opengis.net/kml/2.2");
XmlNode myNode = myXmlDocument.SelectSingleNode("/x:kml/x:Document/x:Placemark/x:Point/x:coordinates", ns);
myNode.InnerText = coordinates;

重要的一点是,您的每个元素都位于名称空间
http://www.opengis.net/kml/2.2
AddNamespace
只是为它添加了一个别名,这样我们就可以方便地讨论名称空间-然后我们使用别名编写xpath,并将名称空间管理器传递给
SelectSingleNode
方法。

您必须使用XmlDocument吗?您完全可以将其用于XmlDocument(问题在于名称空间),但LINQ to XML是一种更现代的API。对我的代码有什么想法吗?我觉得Marc的代码很好。但是如果可能的话,我仍然鼓励您使用LINQ to XML。当您使用
@
symbol@john你说得对,谢谢!:)它不工作我的错误是:对象引用未设置为对象的实例。行内:myNode.Value=坐标;myNolde是空的@VahidNazakTabar我用你发布的xml检查过了。。。它工作得很好;该节点绝对不是
null
。请检查您是否准确地复制了该行。@VahidNazakTabar注意您必须使用
.InnerText
,而不是
.Value
-但这是唯一的其他更改谢谢!它解决了这个问题:XmlNode myNode=myXmlDocument.SelectSingleNode(“/kml/Document/Placemark/Point/coordinates”);右边的代码是:XmlNode myNode=myXmlDocument.SelectSingleNode(“//kml/Document/Placemark/Point/coordinates”);谢谢!:)@Vahid命名空间方法比IMO优越得多:(
XmlNamespaceManager ns = new XmlNamespaceManager(myXmlDocument.NameTable);
ns.AddNamespace("x", "http://www.opengis.net/kml/2.2");
XmlNode myNode = myXmlDocument.SelectSingleNode("/x:kml/x:Document/x:Placemark/x:Point/x:coordinates", ns);
myNode.InnerText = coordinates;