2013-07-24 4 views
0

Я использую using namespace System::Xml; и я хочу легко редактировать XML-файлы (например, записать новое значение для существующего тега <test>)Редактирование XML-файл с C++/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

Смежные вопросы