2012-06-04 43 views
0

我創建一個節點編程,但其中一個屬性出來不同於我在代碼中指定:C#XML屬性正在創建不當

   XmlNode xResource = docXMLFile.CreateNode(XmlNodeType.Element, "resource", docXMLFile.DocumentElement.NamespaceURI); 
       XmlAttribute xRefIdentifier = docXMLFile.CreateAttribute("identifier"); 
       XmlAttribute xRefADLCP = docXMLFile.CreateAttribute("adlcp:scormtype"); 
       XmlAttribute xRefHREF = docXMLFile.CreateAttribute("href"); 
       XmlAttribute xRefType = docXMLFile.CreateAttribute("type"); 
       xRefIdentifier.Value = "RES-" + strRes; 
       xRefADLCP.Value = "sco"; 
       xRefHREF.Value = dataRow["launch_url"].ToString().ToLower(); 
       xRefType.Value = "webcontent"; 

       xResource.Attributes.Append(xRefIdentifier); 
       xResource.Attributes.Append(xRefADLCP); 
       xResource.Attributes.Append(xRefHREF); 
       xResource.Attributes.Append(xRefType); 

這最終建立類似下面的一行。請注意'adlcp:scormtype'已經變成'scormtype',這不是我指定的。任何想法如何讓它顯示我放入CreateAttribute?

<resource identifier="RES-CDA68F64B849460B93BF2840A9487358" scormtype="sco" href="start.html" type="webcontent" /> 

回答

0

這可能是預期的行爲:

的的namespaceURI爲空,除非前綴是公認的內置的前綴,如XMLNS。在這種情況下,NamespaceURI的值爲http://www.w3.org/2000/xmlns/

使用其他替代XmlDocument.CreateAttribute指定的命名空間和前綴:

XmlAttribute xRefADLCP = docXMLFile.CreateAttribute(
    "adlcp","scormtype", "correct-namespace-here"); 
+0

我試着添加這個:XmlAttribute xRefADLCP = docXMLFile.CreateAttribute(「adlcp」,「scormtype」,docXMLFile.DocumentElement.NamespaceURI);問題是它然後爲xmlns添加了另一個屬性:adlcp =「http://www.imsproject.org/xsd/imscp_rootv1p1p2」。任何想法如何擺脫它? – user1366062

+0

您正在重新定義名稱空間。從其他評論的根目錄 - 「xmlns:adlcp =」adlnet.org/xsd/adlcp_rootv1p2「;',從此 - 」xmlns:adlcp =「imsproject.org/xsd/imscp_rootv1p1p2」'。由你決定你想要什麼,如果命名空間相同,我相信在子元素上不會有重複的xmlns屬性。 –

+0

謝謝!我改變它匹配,它消失了。 – user1366062

0

您可以設置Prefix直接的屬性,而不是試圖與前綴在線創建屬性。此覆蓋CreateAttribute與保存文檔合併的

XmlAttribute xRefADLCP = docXMLFile.CreateAttribute("scormtype"); 
// ... 
xRefADLCP.Prefix = "adlcp"; 
xRefADLCP.Value = "sco"; 
+0

出於某種原因,給出了相同的結果,前綴不會出現。我不知道爲什麼。我之前嘗試過,無法啓動它。 – user1366062

+0

@ user1366062您是否在XML文檔中定義了名稱空間?它必須存在(並且在適當的範圍內)確保在適當的地方包含xmlns定義 –

+0

文檔的頂部包含以下內容,我想可以覆蓋它。 user1366062