Copy nested objects from one XmlDocument to another

emaiskkag

New Member
I am at my wits end on this one. Here's the document I have:\[code\]<?xml version="1.0"?><TestObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Property1>TestObjectVal1</Property1> <Property2>TestObjectVal2</Property2> <Property3>TestObjectVal3</Property3> <SubObject> <Prop1>TestObject2Val1</Prop1> <Prop2>TestObject2Val2</Prop2> <Prop3>TestObject2Val3</Prop3> </SubObject></TestObject>\[/code\]I'm trying to copy select portions of it to an new XmlDocument object based on some specified XPaths. I've tried every permutation I can think of. Here's where I'm at now.\[code\]var filters = new[] { "Property1", "Property2", "SubObject/Prop1" };var xmlDoc = GetObjectXml(obj); //Loads the documentvar newDoc = (XmlDocument)xmlDoc.Clone();newDoc.DocumentElement.RemoveAll(); var rootNode = xmlDoc.DocumentElement;foreach (var filter in filters){ var nodes = rootNode.SelectNodes(filter); foreach (XmlNode node in nodes) { var newNode = newDoc.ImportNode(node, true); newDoc.DocumentElement.AppendChild(newNode); }}\[/code\]What I'm getting back is this:\[code\]<?xml version="1.0"?><TestObject> <Property1>TestObjectVal1</Property1> <Property2>TestObjectVal2</Property2> <Prop1>TestObject2Val1</Prop1></TestObject>\[/code\]But I want this:\[code\]<?xml version="1.0"?><TestObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Property1>TestObjectVal1</Property1> <Property2>TestObjectVal2</Property2> <SubObject> <Prop1>TestObject2Val1</Prop1> </SubObject></TestObject>\[/code\]Any idea what I'm doing wrong?
 
Back
Top