2012-03-26 61 views
1

我有一個XML源,其中一個字段是「描述」,它可以在長度上有所不同,但總是相當長。當我將它傳遞給我的asp.net轉發器時,爲了一致性和簡潔起見,我想限制顯示的字符數。有沒有辦法做到這一點?說... 300個字符。如何限制asp.net中XML記錄中顯示的字符數?

預先感謝您!

我的前端代碼:

 <asp:Repeater ID="xPathRepeater" runat="server"> 
     <ItemTemplate> 
      <li> 
       <h3><%#XPath ("title") %></h3> 
       <p><%#XPath("description")%></p> 
      </li> 
     </ItemTemplate> 
     </asp:Repeater> 

我後面的代碼:

protected void XMLsource() 
{ 
    string URLString = "http://ExternalSite.com/xmlfeed.asp"; 

    XmlDataSource x = new XmlDataSource(); 
    x.DataFile = URLString; 
    x.XPath = String.Format(@"root/job [position() < 5]"); 

    xPathRepeater.DataSource = x; 
    xPathRepeater.DataBind(); 
} 

回答

1

我假設XML可以如下所示。從here

<Root> 
    <Row id="1"> 
    <title>contact name 1</name> 
    <desc>contact note 1</note> 
    </Row> 
    <Row id="2"> 
    <title>contact name 2</title> 
    <desc>contact note 2</desc> 
    </Row> 
</Root> 

參考更換你的HTML以下。

<h3><asp:Label ID="title" runat="server"></asp:Label></h3> 
<p><asp:Label ID="desc" runat="server"></asp:Label></p> 

註冊OnItemDataBound事件直放站和編寫以下代碼..

protected void ED_ItemDataBound(object sender, RepeaterItemEventArgs e) 
{ 
    if (e.Item.ItemType == ListItemType.Item) 
    { 
     Label title = (Label)e.Item.FindControl("title"); 
     title.Text = ((System.Xml.XmlElement)e.Item.DataItem).ChildNodes[0].InnerText; 

     Label desc = (Label)e.Item.FindControl("desc"); 
     desc.Text = ((System.Xml.XmlElement)e.Item.DataItem).ChildNodes[1].InnerText.Substring(1, 300) + "..."; 
    } 
} 
+0

有一件事,你可能想要評估'desc.text'確保你不會把一個單詞減半。 – Robert 2012-03-26 20:11:23

+0

@Pankaj,我喜歡你要去的地方。但是,我不確定代碼的工作原理。嘗試訪問XML時遇到錯誤 - 無法轉換類型爲「System.Web.UI.WebControls.XmlDataSourceNodeDescriptor」的對象以鍵入「System.Xml.XmlElement」。 XML與您的示例相同(不包括行ID)。我對Xml不熟悉,無法理解那裏出了什麼問題。 – 2012-03-27 17:19:32

+0

你可以發佈你的示例XML和你使用的代碼嗎? – Pankaj 2012-03-27 17:21:37

3

也許你可以使用子串上返回的XPath查詢的價值?

+0

這似乎是一個不錯的選擇。我如何將它應用於XML記錄?而且,子節點?謝謝!而且要清楚 - 我拉這個XML文件,而不是自己創建它。 – 2012-03-26 18:31:14