C# 中的 XML 替换
我正在尝试使用 ReplaceChild 函数。该代码有效,并且没有引发异常,但是当我将 XML 打印到屏幕上时,该函数似乎不起作用。原始节点是但不是新节点。
private void convertClubComp(XmlDocument doc)
{
XmlNode sessionNode = doc.SelectSingleNode("Session");
XmlNode clubsNode = doc.CreateNode(XmlNodeType.Element, "Clubs", "");
XmlNode playerNode = sessionNode.SelectSingleNode("Players").SelectSingleNode("Player");
XmlNode groupNode = sessionNode.SelectSingleNode("Players").SelectSingleNode("Player").SelectSingleNode("Groups");
Console.WriteLine(playerNode.Name);
clubsNode = doc.ImportNode(groupNode, true);
playerNode.ReplaceChild(clubsNode, sessionNode.SelectSingleNode("Players").SelectSingleNode("Player").SelectSingleNode("Groups"));
Console.WriteLine(clubsNode.FirstChild.FirstChild.Name);
Console.WriteLine("!"+playerNode.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.Name);
}
谢谢
Im trying to use the ReplaceChild function. the code works, and no exceptions are thrown, but when I print XML to the screen it seems as if the function didnt work. the original node is the but not the new one.
private void convertClubComp(XmlDocument doc)
{
XmlNode sessionNode = doc.SelectSingleNode("Session");
XmlNode clubsNode = doc.CreateNode(XmlNodeType.Element, "Clubs", "");
XmlNode playerNode = sessionNode.SelectSingleNode("Players").SelectSingleNode("Player");
XmlNode groupNode = sessionNode.SelectSingleNode("Players").SelectSingleNode("Player").SelectSingleNode("Groups");
Console.WriteLine(playerNode.Name);
clubsNode = doc.ImportNode(groupNode, true);
playerNode.ReplaceChild(clubsNode, sessionNode.SelectSingleNode("Players").SelectSingleNode("Player").SelectSingleNode("Groups"));
Console.WriteLine(clubsNode.FirstChild.FirstChild.Name);
Console.WriteLine("!"+playerNode.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.Name);
}
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,当您执行 ImportNode() 时,它会用另一个节点的克隆替换您对创建的新节点的引用。我认为您正在寻找的内容与此类似:
在单独的说明中,如果您已经有参考,请不要使用 SelectSingleNode() 或 SelectNodes() 。这确实是一种糟糕的做法,在较大的系统中可能会降低你的性能。
Ok, what's happening is when you do the ImportNode() it is replacing your reference to the new node you created with a clone of the other node. I think what you're looking for is something along the lines of this:
On a separate note, don't use SelectSingleNode() or SelectNodes() if you already have a reference. It's really poor practice and in larger systems can kill your performance.