How to can I specify namespace to an XAttribute wh

2019-07-12 02:32发布

All I want to do is an XML document for exporting my datatable to Excel.

So what I need is something like this:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<?mso-application Excel.Sheet?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" />    

I am using System.Xml.Linq and I almost have it, but my code keeps adding "ss" to the front of Workbook. This is my code:

    XDocument xmlssDoc2 = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new 
    XProcessingInstruction("mso-application", "Excel.Sheet"));

    XNamespace aw = "urn:schemas-microsoft-com:office:spreadsheet";
    XNamespace fc = "urn:schemas-microsoft-com:office:spreadsheet";
        XElement root = new XElement(aw + "Workbook",
            new XAttribute("xmlns", "urn:schemas-microsoft-com:office:spreadsheet"),
            new XAttribute(XNamespace.Xmlns + "ss", "urn:schemas-microsoft-com:office:spreadsheet")
        );        

And the result I get is:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<?mso-application Excel.Sheet?>
<ss:Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" />    

Any Help please!

标签: c# xml excel linq
1条回答
淡お忘
2楼-- · 2019-07-12 03:21

From the reference source for XElement, it looks as though the namespace/prefix attribute pairs are pushed onto a push-down stack in order of addition while writing, then checked for matches against the element namespace from top to bottom of the stack -- effectively doing the match in reverse order in which the attributes are added.

So if you add the namespaces in the opposite order, the ss is omitted:

        XDocument xmlssDoc2 = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new
        XProcessingInstruction("mso-application", "Excel.Sheet"));

        XNamespace blank = "urn:schemas-microsoft-com:office:spreadsheet";
        XNamespace ss = "urn:schemas-microsoft-com:office:spreadsheet";

        XElement root = new XElementTest(blank + "Workbook");
        root.Add(new XAttribute(XNamespace.Xmlns + "ss", ss));
        root.Add(new XAttribute("xmlns", blank));

        Debug.WriteLine(root.ToString());

produces:

<Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns="urn:schemas-microsoft-com:office:spreadsheet" />  

Of course, this means that the order of the xmlns attribute specifications has changed, however ideally this should not matter according to the XML specification.

查看更多
登录 后发表回答