2012-05-10 37 views
5

我正在使用SDL Tridion 2011 SP1中的Tom.Net API。 我想檢索XhtmlField的「源」部分。在SDL中使用Tom.Net API獲取Xhtml字段的完整XML源Tridion 2011 SP1

我的源代碼看起來像這樣。

<Content> 
    <text> 
     <p xmlns="http://www.w3.org/1999/xhtml">hello all<strong> 
      <a id="ID1" href="#" name="ZZZ">Name</a> 
     </strong></p> 
    </text> 
</Content> 

我想獲取此「文本」字段的來源並處理名稱爲a的標籤。

我嘗試以下操作:

ItemFields content = new ItemFields(sourcecomp.Content, sourcecomp.Schema); 
XhtmlField textValuesss = (XhtmlField)content["text"]; 

XmlElement textxmlelement = textValuesss.Definition.ExtensionXml; 

Response.Write("<BR>" + "count:" + textxmlelement.ChildNodes.Count); 
for (int i = 0; i < textxmlelement.ChildNodes.Count; i++) 
{ 
    Response.Write("<BR>" + "nodes" + textxmlelement.ChildNodes[i].Name); 
} 

//get all the nodes with the name a 
XmlNodeList nodeswithnameA = textxmlelement.GetElementsByTagName("a"); 
foreach (XmlNode eachNode in nodeswithnameA) 
{ 
    //get the value at the attribute "id" of node "a" 
    string value = eachNode.Attributes["id"].Value; 
    Response.Write("<BR>" + "idValue" + value); 
} 

我沒有得到任何輸出。更重要的是,我將Count算作Zero。

輸出我:

數:0

雖然我已經在該領域的一些子標籤,我沒有得到爲什麼0即將爲Count

任何可以提出需要的修改。

謝謝。

回答

8

ItemField.Definition允許訪問模式定義的字段,而不是字段內容,所以你不應該使用ExtensionXml屬性來訪問內容(這就是爲什麼它是空的)。該屬性用於在模式定義中存儲擴展數據。

要處理包含XML/XHTML內容的字段我只需訪問組件的Content屬性,因爲這已經是一個XmlElement。您需要小心內容的名稱空間,因此在查詢此XmlElement時請使用XmlNamespaceManager。例如,下面會給你到外地命名爲「文」的引用:

XmlNameTable nameTable = new NameTable(); 
XmlNamespaceManager nsManager = new XmlNamespaceManager(nameTable); 
nsManager.AddNamespace("custom", sourceComp.Content.NamespaceURI); 
XmlElement fieldValue = (XmlElement)sourceComp.Content.SelectSingleNode(
           "/custom:Content/custom:text", nsManager); 
2
textValuesss.Definition.ExtensionXml 

這是錯誤的屬性(定義導致Schema字段定義,ExtensionXml用於擴展寫入定製XML數據)。

您想改爲使用textValuesss.Value並將其作爲XML加載。之後,您可能應該使用SelectSingleNode以及包含XHTML名稱空間的特定XPath查詢。或者使用Linq to XML來查找元素。

+0

他尋找多個錨定,所以.SelectNodes()會更好 –

+0

的確。重點是使用XPath而不是循環子節點。 –

相關問題