如何为 XAttribute 指定命名空间,同时拥有另一个具有相同值的命名空间?

2024-02-05

我想要做的只是一个用于将数据表导出到 Excel 的 XML 文档。

所以我需要的是这样的:

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

我在用System.Xml.Linq我几乎已经有了它,但我的代码不断在工作簿的前面添加“ss”。这是我的代码:

    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")
        );        

我得到的结果是:

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

请任何帮助!


来自参考来源 http://referencesource.microsoft.com/#System.Xml.Linq/System/Xml/Linq/XLinq.cs,3e5abc19cad1911d,references for XElement,看起来好像名称空间/前缀属性对被推送到下推堆栈 http://referencesource.microsoft.com/#System.Xml.Linq/System/Xml/Linq/XLinq.cs,84aa37da63f3d367,references按照写入时的添加顺序,然后检查与元素名称空间的匹配从上到下 http://referencesource.microsoft.com/#System.Xml.Linq/System/Xml/Linq/XLinq.cs,151541270dad5982,references堆栈的——有效地以与添加属性相反的顺序进行匹配。

因此,如果您以相反的顺序添加命名空间,ss被省略:

        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());

产生:

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

当然,这意味着xmlns属性规范已经改变,但是理想情况下这应该没关系 http://www.w3.org/TR/REC-xml/#sec-starttags根据 XML 规范。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何为 XAttribute 指定命名空间,同时拥有另一个具有相同值的命名空间? 的相关文章

随机推荐