将XML节点添加为第一个节点 [英] Adding an XML node as the first node
问题描述
任何帮助将不胜感激.我正在尝试找出一种将节点添加到现有XML文件的方法.情况如下:
我想将一个新的"B"节点作为第一个节点-在< A>之后.
每次我尝试添加新节点时,它都会追加到节点列表的底部.
现有文件类似于以下内容:
< A>
< B>
< C/>
< C/>
< C/>
</B>
< B>
< C/>
< C/>
< C/>
</B>
< B>
< C/>
< C/>
< C/>
</B>
</A>
Any help would be greately appreciated. I am trying to figure out a way to add a node to an existing XML file. Here''s the situation:
I want to and a new "B" node as the first node - immediately following <A>.
Each time I tried to add the new node, it''s appended to the bottom of the node list.
The existing file resembling the following:
<A>
<B>
<C />
<C />
<C />
</B>
<B>
<C />
<C />
<C />
</B>
<B>
<C />
<C />
<C />
</B>
</A>
推荐答案
我不知道您使用的是哪种语言,但是对于System.Xml,您使用的是XmlNode.InsertBefore [
I do not know which language you are using but for System.Xml you use the XmlNode.InsertBefore[^] Method.
See the example in the documentation.
You want to useInserBefore
to add a new node before the first child of <A>.
回复给Andre.谢谢您的帮助.我正在使用C Sharp.
当我使用InsertBefore时,我得到以下信息:
引用节点不是此节点的子级."
代码如下:
字符串xmlTemp ="C:\\ Users \\ User \\ Documents \\ My Projects \\ temp.xml";
XmlDocument xmlDoc =新的XmlDocument();
xmlDoc.Load(xmlTemp);
XmlNode nodeA = xmlDoc.SelectSingleNode("A");
XmlNode nodeB = xmlDoc.CreateNode(XmlNodeType.Element,"B",null);
XmlNode nodeC = xmlDoc.CreateNode(XmlNodeType.Element,"C",null);
nodeA.InsertBefore(nodeB,xmlDoc.FirstChild);
nodeB.AppendChild(nodeC);
xmlDoc.Save(xmlTemp);
Reply to Andre. Thanks for the help. I''m using C Sharp.
And when I use InsertBefore I get the following:
"The reference node is not a child of this node."
Here''s the code:
string xmlTemp = "C:\\Users\\User\\Documents\\My Projects\\temp.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlTemp);
XmlNode nodeA = xmlDoc.SelectSingleNode("A");
XmlNode nodeB = xmlDoc.CreateNode(XmlNodeType.Element, "B", null);
XmlNode nodeC = xmlDoc.CreateNode(XmlNodeType.Element, "C", null);
nodeA.InsertBefore(nodeB, xmlDoc.FirstChild);
nodeB.AppendChild(nodeC);
xmlDoc.Save(xmlTemp);
问题已解决.谢谢,安德烈
Problem solved. Thanks, Andre
这篇关于将XML节点添加为第一个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!