将嵌套对象从一个XmlDocument复制到另一个XmlDocument

时间:2012-06-13 02:32:44

标签: c# xml parsing xml-serialization xml-parsing

我在这个问题上的斗智尽头。这是我的文件:

<?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>

知道我做错了吗?

1 个答案:

答案 0 :(得分:0)

看起来问题是xpath方法正在选择内部元素,因此* SubObject“信息会丢失。此代码应该为您的特定示例生成正确的输出。

foreach (XmlNode node in nodes)
{
    XmlElement newNode; 
    string[] xpathElements = filter.Split('/');
    if (xpathElement.Length == 2) 
    {
        newNode = newDoc.CreateElement(filter);
        newNode.AppendChild(newDoc.ImportNode(node, true));

    }
    else 
    {
        newNode = newDoc.ImportNode(node, true);
    }
    newDoc.DocumentElement.AppendChild(newNode);
}

请注意,此代码对“过滤器”xpath表达式必须采用的形式进行限制性假设...即,它必须是“RootElement”或“RootElement / ChildElement”形式(没有属性,最大深度为3) 。根据您的使用情况,这可能就足够了,但解决更一般的情况会更棘手......

相关问题