【发布时间】:2010-11-10 03:27:16
【问题描述】:
我试图在另一个 xmlnode 之前插入一个 xml 节点,但出现异常提示“引用节点不是此节点的子节点。”
这是我的初始 xml:
<?xml version="1.0" encoding="utf-8" ?>
<Details xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<sampleData>
<otherNodes></otherNodes>
</sampleData>
</Details>
我想插入以下 xml 数据(b:dataTobeInserted1,b:dataTobeInserted2 和 b:dataTobeInserted3)作为 Details 的子级,但在 sampleData 之前。
Details1.xml
<?xml version="1.0" encoding="utf-8" ?>
<DataInserted1 xmlns:b="http://example.com/data">
<b:dataTobeInserted1>
<b:otherDetails1></b:otherDetails1>
</b:dataTobeInserted1>
</DataInserted1>
Details2.xml
<?xml version="1.0" encoding="utf-8" ?>
<DataInserted2 xmlns:b="http://example.com/data">
<b:dataTobeInserted2>
<b:otherDetails2></b:otherDetails2>
</b:dataTobeInserted2>
</DataInserted2>
Details3.xml
<?xml version="1.0" encoding="utf-8" ?>
<DataInserted3 xmlns:b="http://example.com/data">
<b:dataTobeInserted3>
<b:otherDetails3></b:otherDetails3>
</b:dataTobeInserted3>
</DataInserted3>
我希望我的输出为
<?xml version="1.0" encoding="utf-8" ?>
<Details xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:b="http://example.com/data">
<b:dataTobeInserted1>
<b:otherDetails1></b:otherDetails1>
</b:dataTobeInserted1>
<b:dataTobeInserted2>
<b:otherDetails2></b:otherDetails2>
</b:dataTobeInserted2>
<b:dataTobeInserted3>
<b:otherDetails3></b:otherDetails3>
</b:dataTobeInserted3>
<sampleData>
<otherNodes></otherNodes>
</sampleData>
</Details>
这是我为实现我想要的输出所做的。
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(@"..\..\initial-Doc.xml");
xmldoc.DocumentElement.SetAttribute("xmlns:b", "http://example.com/data");
XmlDocument detail1 = new XmlDocument();
detail1.Load(@"..\..\DataToBeInserted1.xml");
XmlNode detail1Node = xmldoc.ImportNode(detail1.DocumentElement, true);
XmlDocument detail2 = new XmlDocument();
detail2.Load(@"..\..\DataToBeInserted2.xml");
XmlNode detail2Node = xmldoc.ImportNode(detail2.DocumentElement, true);
XmlDocument detail3 = new XmlDocument();
detail3.Load(@"..\..\DataToBeInserted3.xml");
XmlNode detail3Node = xmldoc.ImportNode(detail3.DocumentElement, true);
xmldoc.InsertBefore(detail1Node, xmldoc.DocumentElement.FirstChild);
xmldoc.InsertBefore(detail2Node, xmldoc.DocumentElement.FirstChild);
xmldoc.InsertBefore(detail3Node, xmldoc.DocumentElement.FirstChild);
xmldoc.Save(@"..\..\initial-Doc-new.xml");
是新命名空间导致问题吗?请告诉我哪里出错了。
谢谢 亚历克斯
【问题讨论】: