Saravanan
Saravanan

Reputation: 11602

how to replace xml elements with another xml elements in c#?

This is my two xml document.

This xml is stored in paraouterXml string.

<w:tbl>
 <w:tblPr>
 </w:tblPr>
 <w:tblGrid>
 </w:tblGrid>
</w:tbl>

This xml is stored in tblMetaInfo string.

<root>
 <w:tblPr>
  <w:tblStyle w:val="TableGrid" /> 
  <w:tblW w:w="0" w:type="auto" /> 
  <w:tblLook w:val="04A0" /> 
  </w:tblPr>
 <w:tblGrid>
  <w:gridCol w:w="1947" /> 
  <w:gridCol w:w="1947" /> 
  </w:tblGrid>
</root>

So,here i want to replace paraouterXml's <w:tblPr>,<w:tblGrid> with tblMetaInfo's <w:tblPr>,<w:tblGrid> elements.

This is c# code...

XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(table.OuterXml);
XmlNode newNode = xDoc.DocumentElement;

XmlNodeList tblPrNode = xDoc.GetElementsByTagName("w:tblPr");
tblPrNode[0].RemoveAll();
XmlNodeList tblGridNode = xDoc.GetElementsByTagName("w:tblGrid");
tblGridNode[0].RemoveAll();

XmlDocument xDoc1 = new XmlDocument();
xDoc1.LoadXml(tblMetaInfo);
XmlNode newNode1 = xDoc1.DocumentElement;
XmlNodeList tblPrNode1 = xDoc1.GetElementsByTagName("w:tblPr");
XmlNodeList tblGridNode1 = xDoc1.GetElementsByTagName("w:tblGrid");

tblPrNode[0].ReplaceChild(tblPrNode1[0], tblPrNode[0]);
tblGridNode[0].ReplaceChild(tblGridNode1[0], tblGridNode[0]);

But it throwing some error...

Please guide me to get out of this issue...

Upvotes: 1

Views: 5135

Answers (1)

Ria
Ria

Reputation: 10357

ArgumentException: The newChild was created from a different document than the one that created this node.

public XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild):

If the newChild was created from another document, you can use XmlDocument.ImportNode to import the node to the current document. The imported node can then be passed to the ReplaceChild method.

Upvotes: 5

Related Questions