我对此一无所知。这是我的文件:
<?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>
我正在尝试将它的选定部分复制到基于某些指定 XPath 的新 XmlDocument 对象。我已经尝试了所有我能想到的排列方式。这就是我现在的位置。
var filters = new[] { "Property1", "Property2", "SubObject/Prop1" };
var xmlDoc = GetObjectXml(obj); //Loads the document
var 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);
}
}
我得到的是这样的:
<?xml version="1.0"?>
<TestObject>
<Property1>TestObjectVal1</Property1>
<Property2>TestObjectVal2</Property2>
<Prop1>TestObject2Val1</Prop1>
</TestObject>
但我想要这个:
<?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>
知道我做错了什么吗?