XML格式生成问题

时间:2019-01-29 18:02:18

标签: c# xml

我正在尝试使用XML生成一个XDocument文档:

   public class BuildXML
        {
           static void Main( string[ ] args ) {
              XDocument doc = new XDocument(
                new XElement("FolioIdentifiers",
                new XElement("FolioId", "6798634B2F7")),
                                         //);

                 new XElement("DocumentAuthentication",
                 new XElement("ScannedDocuments",
                 new XElement("ScannedDocument",
                 new XElement("DocumentType", "AppliationForm")))));

        doc.Save("C:\\document.xml");

运行它时,出现此错误:

This operation would create an incorrectly structured document.

我使用的格式错误吗?

2 个答案:

答案 0 :(得分:3)

XML文档只能有一个根节点。就您而言,您有两个:FolioIdentifiersDocumentAuthentication。如果我调整您的格式,将更容易看到。

public class BuildXML
{
    static void Main( string[ ] args )
    {
        XDocument doc = new XDocument(
            //At root level
            new XElement("FolioIdentifiers",
                new XElement("FolioId", "6798634B2F7")),

            //Also at root level (BAD! - this is what causes the incorrect structure error)
            new XElement("DocumentAuthentication",
                new XElement("ScannedDocuments",
                    new XElement("ScannedDocument",
                        new XElement("DocumentType", "AppliationForm")))));

        doc.Save("C:\\document.xml");
    }  
}

答案 1 :(得分:0)

通过将“ FolioIdentifiers”设为根元素,可以轻松解决该错误,从而使您在根目录下没有数组。只需移动括号即可解决:

             XDocument doc = new XDocument(
                new XElement("FolioIdentifiers", new object[] {
                new XElement("FolioId", "6798634B2F7"),
                 new XElement("DocumentAuthentication",
                 new XElement("ScannedDocuments",
                 new XElement("ScannedDocument",
                 new XElement("DocumentType", "AppliationForm"))))}));