2017-03-18 22 views
0

創建XML下面的XML在我需要的輸出如何使用多根元素

<?xml version="1.0" encoding="UTF-8"?> 
<units> 
    <unit> 
     <unit-info xmlns=""> 
      <unit-id>4550669</unit-id> 
      <order-id>11949776</order-id> 
      <parcel-id>none</parcel-id> 
      <supplier-id>6</supplier-id> 
     </unit-info> 
    </unit> 
</units> 

的,我用下面的C#代碼:

XDocument Document = new XDocument(); 
    XDeclaration declaration = new XDeclaration("1.0", "UTF-8", null); 
    Document.Declaration = declaration; 
    XNamespace ns = "http://www.elsevier.com/xml/ani/ani"; 
    XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; 
    XNamespace ce = "http://www.elsevier.com/xml/ani/common"; 

    XElement nameSpaceElement = new XElement(
      ns + "units", new XAttribute("xmlns", ns), new XAttribute(XNamespace.Xmlns + "xsi", xsi), new XAttribute(XNamespace.Xmlns + "ce", ce), new XAttribute(xsi + "schemaLocation", 
    "http://www.elsevier.com/xml/ani/ani http://www.elsevier.com/xml/ani/ani512-input-CAR.xsd"),Document.Root); 

    Document.Add(nameSpaceElement); 
    XElement uniType = new XElement("unit", new XAttribute("type", "ARTICLE")); 

    Document.Root.Add(uniType); 

    XElement unitInfo = new XElement("unit-info", new XElement("unit-id", "4550669"), new XElement("order-id", "11949776"), new XElement("parcel-id", "none"), new XElement("supplier-id", "6"), new XElement("timestamp", DateTime.Now)); 
    Document.Root.Add(unitInfo); 
    Document.Save("document.txt"); 

但我得到的輸出類似下面的文檔

<units> 
    <unit></unit> 
    <unit-info xmlns=""> 
    <unit-id>4550669</unit-id> 
    <order-id>11949776</order-id> 
    <parcel-id>none</parcel-id> 
    <supplier-id>6</supplier-id> 
    </unit-info> 
</units> 

這裏我的第二個元素在那裏封閉。但是我需要像根元素一樣關閉那個元素。

如何讓我出去用XDocumentXElement

+0

相反Document.Root.Add(unitInfo)的',''做uniType.Add(unitInfo);' – rene

+0

是的,我得到了答案 –

+1

XML不支持多個根元素 –

回答

0

您應該將您的unitInfo添加到uniType,而不是直接添加到根目錄。

像uniType.Add(unitInfo),而不是 Document.Root.Add(unitInfo)

相關問題