【问题标题】:How to make an XML header with given attributes in LINQ-to-XML?如何在 LINQ-to-XML 中创建具有给定属性的 XML 标头?
【发布时间】:2012-02-27 14:41:37
【问题描述】:

我需要使用 LINQ to XML 和 C# 重现以下 XML 标头:

<ns0:Subject_Sample xmlns:ns0="fhrb"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="fhrb file:FHRB_NEW_SUBJECT_SAMPLE.xsd" >

第一个问题是,当我改编 .NET 帮助示例时,标题中的内容开始消失。例如:

XElement myTree = new XElement(ns0 + "Subject_Sample",
            new XAttribute(XNamespace.Xmlns + "ns0", "http://www.adventure-works.com" )         
        ); 

提供我需要的东西

 <ns0:Subject_Sample xmlns:ns0="http://www.adventure-works.com"> 

但是如果我将 XAttribute 参数从 web URL 更改为字符串(例如“fhrb”),那么由于某种原因“ns0:”从标签中消失了(ns0:Subject_Sample 变成了 Subject_Sample)。

然后,我决定尝试通过以下代码制作 schemaLocation 属性:

XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XNamespace ns0 = "http://www.adventure-works.com";
XElement myTree = new XElement(ns0 + "Subject_Sample",
new XAttribute(XNamespace.Xmlns + "ns0", "http://www.adventure-works.com" ),
            new XAttribute(xsi+"schemaLocation", "fhrb file:/fhrb.xsd")); 

但我得到的结果如下,奇怪的p1出现了。

 <ns0:Subject_Sample xmlns:ns0="http://www.adventure-works.com" p1:schemaLocation="fhrb file:/fhrb.xsd" xmlns:p1="http://www.w3.org/2001/XMLSchema-instance"> 

问题是:如何通过 LINQ to XML 重现所需的标头格式?这些属性的出现/消失/命名背后的逻辑是什么?

【问题讨论】:

    标签: c# .net xml linq linq-to-xml


    【解决方案1】:

    试试这个:

    XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
    XNamespace ns0 = "fhrb";
    XElement myTree = new XElement(ns0 + "Subject_Sample",
                                      new XAttribute(XNamespace.Xmlns + "xsi", xsi),
                                      new XAttribute(XNamespace.Xmlns + "ns0", ns0),
                                      new XAttribute(xsi + "schemaLocation", "fhrb file:FHRB_NEW_SUBJECT_SAMPLE.xsd")
                                  );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-22
      • 2013-09-23
      相关资源
      最近更新 更多