2012-02-27 67 views
-1

我需要複製使用LINQ to XML和C#以下XML頭:如何使用LINQ-to-XML中的給定屬性製作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"> 

,但如果我從網頁URL更改XAttribute參數字符串(如「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重現所需的頭部格式?這些屬性的出現/消失/命名背後的邏輯是什麼?

回答

0

試試這個:

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