简体   繁体   中英

How do I limit the number of characters shown in an XML record in asp.net?

I have an XML source and one of the fields is "description" which can vary in length but is always rather long. When I'm passing this to my asp.net repeater, I'd like to limit the number of characters that are displayed for consistency and brevity's sake. Is there any way to do this? Say... 300 characters.

Thank you in advance!

My front end code:

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

My code behind:

    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();
}

也许你可以在返回的XPath查询的值上使用SubString?

I assume the XML can be like below.

<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>

Reference from here

Replace your HTML to following.

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

Register the OnItemDataBound Event of Repeater and write the following code..

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) + "...";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM