【问题标题】:Copy nested objects from one XmlDocument to another将嵌套对象从一个 XmlDocument 复制到另一个
【发布时间】:2012-06-15 23:23:52
【问题描述】:

我对此一无所知。这是我的文件:

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

知道我做错了什么吗?

【问题讨论】:

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


    【解决方案1】:

    看起来问题在于 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”形式(没有属性,最大深度为三) .根据您的用例,这可能就足够了,但解决更一般的情况会有点棘手......

    【讨论】:

      猜你喜欢
      • 2011-01-26
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-04
      • 1970-01-01
      相关资源
      最近更新 更多