我有以下XML结构,以便我可以将配置详细信息添加到lastconnected元素:
<?xml version="1.0" encoding="utf-8" ?>
<lastconnectedServers>
</lastconnectedServers >
现在我想做一些XML操作,比如添加元素和属性。例如,我想将元素添加到上面的xml :(在elemet lastconnectedServers内部):
<Server ip="" domain="">
<SharedFolder name="" type=""/>
<SharedFolder name="" type =""/>
<SharedFolder name="" type =""/>
</Server>
以便生成的XML看起来如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<lastconnectedServers>
<Server ip="" domain="">
<SharedFolder name="" type=""/>
<SharedFolder name="" type =""/>
<SharedFolder name="" type =""/>
</Server>
</lastconnectedServers >
答案 0 :(得分:3)
以下是使用MSXML的示例代码。省略COM错误检查。由于用于COM的ATL助手,代码看起来有点罗嗦,但编程模型遵循W3C DOM API,这是xml开发人员非常接受的。
CComPtr<IXMLDOMDocument2> spDoc;
CComPtr<IXMLDOMElement> spServerElement, spSharedFolderElement;
CComPtr<IXMLDOMNode> spServerNode, spLastConnectedServerNode;
IXMLDOMNode* pInsertedNode;
VARIANT_BOOL varSucc;
CComBSTR bstrLastConnected = L"<?xml version=\"1.0\" encoding=\"utf-8\" ?> \
<lastconnectedServers> \
</lastconnectedServers >";
spDoc.CoCreateInstance(CLSID_DOMDocument60, NULL, CLSCTX_INPROC_SERVER);
spDoc->put_async(VARIANT_FALSE);
spDoc->loadXML(bstrLastConnected, &varSucc);
// Finds the lastConnectedServerNode node with XPath.
spDoc->selectSingleNode(CComBSTR(L"/lastconnectedServers"),
&spLastConnectedServerNode);
// Creates and appends Server node.
spDoc->createElement(CComBSTR(L"Server"), &spServerElement);
spServerElement->setAttribute(CComBSTR(L"ip"), CComVariant(L""));
spServerElement->setAttribute(CComBSTR(L"domain"), CComVariant(L""));
spLastConnectedServerNode->appendChild(spServerElement, &pInsertedNode);
// Creates and appends the first SharedFolder elements.
spDoc->createElement(CComBSTR(L"SharedFolder"), &spSharedFolderElement);
spSharedFolderElement->setAttribute(CComBSTR(L"name"), CComVariant(L""));
spSharedFolderElement->setAttribute(CComBSTR(L"type"), CComVariant(L""));
spServerElement->appendChild(spSharedFolderElement, &pInsertedNode);
// Creates the second and third SharedFolder elements...
// Gets the xml content.
CComBSTR bstrXml;
spDoc->get_xml(&bstrXml);
wprintf(L"%s", (LPCWSTR) bstrXml);
希望这有帮助。
答案 1 :(得分:2)
TiXmlDocument doc("YourFile.xml");
bool loadOkay = doc.LoadFile();
if(loadOkay)
{
//Variables for XML elements and attributes
TiXmlElement *pRoot;
//Get root element
pRoot = doc.RootElement();
TiXmlElement * server = new TiXmlElement("Server"); // Create the new child element
server->LinkEndChild(pRoot);//Links the child to the parent
server->setAttribute("ip", ""); // Set attributes
server-setAttribute("domain","");
foeach(/*Your Data as Value*/)
{
TiXmlElement * sharedFolder = new TiXmlElement("SharedFolder");
server->LinkEndChild(sharedFolder);
server->setAttribute("name", "");
server-setAttribute("type","");
}
}
if( doc.SaveFile( "YourOutput.xml" ))
{
return true;
}
else
{
return false;
}
这应该允许您将新子项添加到根元素,并且是执行此操作的基本结构。您可以找到有关TinxyXML及其使用方法的更多信息here