2017-06-06 41 views
0

我有一个XML文档,基本上是这样的:XmlDocumentFragment设置InnerXml失败,并没有宣布前缀

<ArrayOfAspect xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
    <Aspect i:type="TransactionAspect"> 
     ... 
    </Aspect> 
    <Aspect i:type="TransactionAspect"> 
     ... 
    </Aspect> 
</ArrayOfAspect> 

而且我想一个新的Aspect添加到这个列表。
为了做到这一点,我加载这个XML文件,创建一个XmlDocumentFragment并从一个文件(这基本上是一个模板填充数据)加载新的方面。然后我用新的方面填充文档片段并将其作为一个孩子添加。
但是,当我尝试设置此片段的xml它失败,因为没有定义前缀i

// Load all aspects 
var aspectsXml = new XmlDocument(); 
aspectsXml.Load("aspects.xml"); 

// Create and fill the fragment 
var fragment = aspectsXml.CreateDocumentFragment(); 
fragment.InnerXml = _templateIFilledWithData; // This fails because i is not defined 

// Add the new child 
aspectsXml.AppendChild(fragment) 

这是模板的样子:

<Aspect i:type="TransactionAspect"> 
    <Value>$VALUES_PLACEHOLDER$</Value> 
    ... 
</Aspect> 

请注意,我不希望创建波苏斯,这和它们序列化,因为各方面都actualy相当大的和嵌套和我有与其他一些xml文件一样的问题也是如此。


编辑:
jdweng建议使用XmlLinq(这是远远比我以前使用的更好,这样的感谢)。下面是我尝试用XmlLinq(仍失败,因为未申报的前缀)使用代码:

var aspects = XDocument.Load("aspects.xml"); 
var newAspects = EXlement.Parse(_templateIFilledWithData); // Fails here - Undeclared prefix 'i' 
aspects.Root.add(newAspect); 

回答

0

使用XML LINQ:

using System.Collections.ObjectModel; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 



namespace ConsoleApplication57 
{ 
    class Program 
    { 
     const string URL = "http://goalserve.com/samples/soccer_inplay.xml"; 
     static void Main(string[] args) 
     { 
      string xml = 
       "<ArrayOfAspect xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" + 
        "<Aspect i:type=\"TransactionAspect\">" + 
        "</Aspect>" + 
        "<Aspect i:type=\"TransactionAspect\">" + 
        "</Aspect>" + 
       "</ArrayOfAspect>"; 

      XDocument doc = XDocument.Parse(xml); 

      XElement root = doc.Root; 
      XNamespace nsI = root.GetNamespaceOfPrefix("i"); 

      root.Add(new XElement("Aspect", new object[] { 
       new XAttribute(nsI + "type", "TransactionAspect"), 
       new XElement("Value", "$VALUES_PLACEHOLDER$") 
      })); 


     } 

    } 

} 
+0

我不想手动生成代码的方面,因为它是一个非常大的对象,我有模板文件,很容易填充数据。 – danielspaniol

+0

您可以读取模板文件,然后根据需要修改/添加元素。你可以使用Load(filename)方法读取文件(而不是解析(字符串),然后搜索元素位置来修改/添加元素。我刚刚发布了示例代码,以便您可以看到如何启动。您的原始问题是命名空间'我编写的代码如下: – jdweng

+0

我如何将用XDocument.Parse()创建的XDocument添加到我的容器元素中? - 编辑:自己找到了'XElement.Parse()' – danielspaniol