我以前做过这样的事情。我正在使用 LINQ to XML。我为 XElement 创建了一个扩展方法,它采用节点名称队列和列表中最后一个节点的值。这是我做的扩展方法:
/// <summary>
/// Creates nessecary parent nodes using the provided Queue, and assigns the value to the last child node.
/// </summary>
/// <param name="ele">XElement to take action on</param>
/// <param name="nodes">Queue of node names</param>
/// <param name="value">Value for last child node</param>
public static void UpdateOrCreate(this XElement ele, Queue<string> nodes, string value)
{
string previousNodeName = "";
int fullQueueCOunt = nodes.Count;
for (int i = 0; i < fullQueueCOunt; i++)
{
string node = nodes.Dequeue();
if (ele.Descendants(node).FirstOrDefault() == null)
{
if (!string.IsNullOrEmpty(previousNodeName))
{
ele.Element(previousNodeName).Add(new XElement(node));
}
else
{
// use main parent node if this is the first iteration
ele.Add(new XElement(node));
}
}
previousNodeName = node;
}
// assign the value of the last child element
ele.Descendants(previousNodeName).First().Value = value;
}
这是一个示例实现:
XElement element = XElement.Parse(
"<employee>" +
"<name>John Smith</name>" +
"</employee>");
Queue<string> nodeQueue = new Queue<string>();
nodeQueue.Enqueue("address");
nodeQueue.Enqueue("city");
element.UpdateOrCreate(nodeQueue, "myValue");
这将采用输入 XML:
<employee>
<name>John Smith</name>
</employee>
并将其更改为:
<employee>
<name>John Smith</name>
<address>
<city>myValue</city>
</address>
</employee>
如果“地址”和/或“城市”节点已经存在,这也将起作用。