【发布时间】:2009-05-14 11:59:51
【问题描述】:
我是 C# 中 XML 和 XPath 的初学者。这是我的 XML 文档的示例:
<root>
<folder1>
...
<folderN>
...
<nodeMustExist>...
<nodeToBeUpdated>some value</nodeToBeUpdated>
....
</root>
如果节点存在,我需要更新 nodeToBeUdpated 的值,或者如果 nodeToBeUpdated 不存在,则在 nodeMustExist 之后添加此节点。函数的原型是这样的:
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;
}
}
*/
}
也许还有其他更好、更简化的方法可以做到这一点。有什么建议吗?
顺便说一句,如果nodeToBeUpdated在其他地方出现了不止一次,我只想更新第一个。
【问题讨论】:
-
我更改了您方法的签名格式以摆脱水平滚动。我讨厌水平滚动。