Updating or inserting a node in an XML document
I am getting started with XML and XPath in C #. Here's an example of my XML document:
<root>
<folder1>
...
<folderN>
...
<nodeMustExist>...
<nodeToBeUpdated>some value</nodeToBeUpdated>
....
</root>
I need to update the nodeToBeUdpated value if a node exists, or add this node after nodeMustExist if nodeToBeUpdated does not exist. The function prototype is something like this:
void UpdateNode(
xmlDocument xml,
string nodeMustExist,
string nodeToBeUpdte,
string newVal
)
{
/*
search for XMLNode with name = nodeToBeUpdate in xml
to XmlNodeToBeUpdated (XmlNode type?)
if (xmlNodeToBeUpdated != null)
{
xmlNodeToBeUpdated.value(?) = newVal;
}
else
{
search for nodeMustExist in xml to xmlNodeMustExist obj
if ( xmlNodeMustExist != null )
{
add xmlNodeToBeUpdated as next node
xmlNodeToBeUpdte.value = newVal;
}
}
*/
}
Maybe there is another better and simplified way to do this. Any advice?
By the way, if nodeToBeUpdated appears more than once elsewhere, I just want to update the first one.
a source to share
This update is all nodes in the folder:
public void UpdateNodes(XmlDocument doc, string newVal)
{
XmlNodeList folderNodes = doc.SelectNodes("folder");
if (folderNodes.Count > 0)
foreach (XmlNode folderNode in folderNodes)
{
XmlNode updateNode = folderNode.SelectSingleNode("nodeToBeUpdated");
XmlNode mustExistNode = folderNode.SelectSingleNode("nodeMustExist"); ;
if (updateNode != null)
{
updateNode.InnerText = newVal;
}
else if (mustExistNode != null)
{
XmlNode node = folderNode.OwnerDocument.CreateNode(XmlNodeType.Element, "nodeToBeUpdated", null);
node.InnerText = newVal;
folderNode.AppendChild(node);
}
}
}
If you want to update a specific node, you won't be able to pass the string nodeToBeUpdte, but you will need to pass the XmlNode to the XmlDocument. I missed going through the node names in the function as the node names are unlikely to change and can be hardcoded. However, you can pass them to functions and use strings instead of hard-coded node names.
a source to share
An XPath expression that selects all instances <nodeToBeUpdated>
would be:
/ root / folder [nodeMustExist] / nodeToBeUpdated
or more generally:
/ root / folder [* [name () = 'nodeMustExist']] / * [name () = 'nodeToBeUpdated']
suitable for:
void UpdateNode(xmlDocument xml,
string nodeMustExist,
string nodeToBeUpdte,
string newVal)
{
string xPath = "/root/folder[*[name() = '{0}']]/*[name() = '{1}']";
xPath = String.Format(xPath, nodeMustExist, nodeToBeUpdte);
foreach (XmlNode n in xml.SelectNodes(xPath))
{
n.Value = newVal;
}
}
a source to share
Have a look at the SelectSingleNode method MSDN Domain
your xpath wants to be something like "// YourNodeNameHere";
after you find that a node, you can do a reverse copy of the tree to navigate to the "nodeMustExist" node:
XmlNode nodeMustExistNode = yourNode.Parent["nodeMustExist];
a source to share