【问题标题】:How to can I specify namespace to an XAttribute while having another namespace with the same value?如何在另一个具有相同值的命名空间的同时为 XAttribute 指定命名空间?
【发布时间】:2014-12-03 18:20:46
【问题描述】:

我想要做的只是一个用于将我的数据表导出到 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,我几乎拥有它,但我的代码不断在 Workbook 的前面添加“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" />    

请帮忙!

【问题讨论】:

    标签: c# xml excel linq


    【解决方案1】:

    XElementreference source 来看,看起来命名空间/前缀属性对在写入时按添加顺序推送到push-down stack,然后检查来自top to bottom 的元素命名空间是否匹配堆栈——有效地以添加属性的相反顺序进行匹配。

    因此,如果您以相反的顺序添加命名空间,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 属性规范的顺序已经改变,但是根据 XML 规范,这个should not matter 是理想的。

    【讨论】:

    • 干得好!我在前一天问了这个问题,实际上最终做了类似的事情,但你的答案是正确的!谢谢 dbc!
    猜你喜欢
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 1970-01-01
    • 2014-09-27
    • 2011-04-10
    • 1970-01-01
    • 2012-09-12
    相关资源
    最近更新 更多