2013-07-24 70 views
0

我使用using namespace System::Xml;,我想轻松地编辑XML文件(例如写现有标签<test>一个新的值)编辑XML文件++/CLI

示例XML

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

我该怎么办这个? (与XmlTextWriter对象和XmlTextReader的?)

THX

+0

参考你知道怎么做,在C#或其他纯托管语言? –

回答

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 
+0

这并不回答你的问题,你坚持使用XmlTextWriter和XmlTextReader。 –

+0

你看到“?”在XmlTextWriter和XmlTextReader之后?这只是一个想法,它可以工作! – leon22

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的