0

我正在使用using namespace System::Xml;并且我想轻松地编辑 xml 文件(例如,为现有标签写一个新值<test>

示例 XML

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>  
  <test>VALUE</test>
</note>

我怎样才能做到这一点?(使用 XmlTextWriter 和 XmlTextReader?)

谢谢

4

2 回答 2

1
System::Xml::Linq::XDocument^ doc = System::Xml::Linq::XDocument::Load("q.xml");
doc->Root->Element("test")->Value = "zz"; 
doc->Save("q.xml");

参考 System.Xml.Linq

于 2013-07-24T15:43:18.570 回答
0
// open XML file
System::Xml::XmlDocument xmlDoc;
xmlDoc.Load("Test.xml");

// find desired node
XmlNode ^node = xmlDoc.SelectSingleNode("//test");

if (node != null)
{
    node->InnerText = "NEWVALUE"; // write new value 
}
else // if the node is not present in the xml file
{
    XmlNode ^root = xmlDoc.DocumentElement;
    XmlElement ^elem = xmlDoc.CreateElement("key");
    elem->InnerText = "NEWVALUE";
    root->AppendChild(elem);
}

// if you want to write the whole xml file to a System::String
StringWriter ^stringWriter = gcnew StringWriter();
XmlTextWriter ^xmlWriter = gcnew XmlTextWriter(stringWriter);
xmlDoc.WriteTo(xmlWriter);  

System::String ^str = stringWriter->ToString();

xmlDoc.Save("Test.xml"); // finally save the changes to xml file
于 2013-07-24T14:46:18.317 回答