【问题标题】:How do I limit the number of characters shown in an XML record in asp.net?如何限制 asp.net 中 XML 记录中显示的字符数?
【发布时间】:2012-03-26 17:55:28
【问题描述】:

我有一个 XML 源,其​​中一个字段是“描述”,它的长度可能会有所不同,但总是很长。当我将它传递给我的 asp.net 中继器时,为了保持一致性和简洁性,我想限制显示的字符数。有没有办法做到这一点?说... 300 个字符。

提前谢谢你!

我的前端代码:

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

【问题讨论】:

    标签: c# asp.net xml asprepeater


    【解决方案1】:

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

    【讨论】:

    • 这似乎是一个不错的选择。我将如何将其应用于 XML 记录?而且,子节点呢?谢谢!需要明确的是,我是在提取这个 XML 文件,而不是自己创建它。
    【解决方案2】:

    我假设 XML 可以如下所示。

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

    来自here

    的参考资料

    将您的 HTML 替换为以下内容。

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

    注册Repeater的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) + "...";
        }
    }
    

    【讨论】:

    • 一件事,您可能需要评估desc.text 以确保您没有将一个词切成两半。
    • @Pankaj,我喜欢你用这个去哪里。但是,我不确定代码是否有效。尝试访问 XML 时出现错误 - 无法将“System.Web.UI.WebControls.XmlDataSourceNodeDescriptor”类型的对象转换为“System.Xml.XmlElement”类型。 XML 与您的示例相同(减去行 ID)。我对 Xml 不够熟悉,无法理解那里出了什么问题。
    • 您可以发布您的示例 XML 和您正在使用的代码吗?
    猜你喜欢
    • 2020-07-30
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    相关资源
    最近更新 更多