【问题标题】:Apostrophes in XML and Databound ControlsXML 和数据绑定控件中的撇号
【发布时间】:2011-01-22 09:52:43
【问题描述】:

在我的 XML 中,撇号可能出现在节点的值中:

<Root>
    <Sections>
        <SectionA>
            <Heading>Title</Heading>
            <Description>This is section 'A'</Description>
        </SectionA>
    </Sections>
</Root>

如果我有绑定到这个 XML 的控件:

<asp:FormView ID="myFormView" runat="server" DataSourceID="myXmlDataSource">
    <ItemTemplate>
        <div>
            HTML Element:
            <input type="text" value='<%# XPath("text()") %>' />
        </div>
        <div>    
            Server Control:
            <asp:TextBox id="myTextBox" runat="server" value='<%# XPath("text()") %>' />
        </div>
    </ItemTemplate>
</asp:FormView>           
<asp:XmlDataSource ID="myXmlDataSource" runat="server" XPath="Root/Sections/SectionA" />

我注意到文本在 asp:TextBox 中正确显示,但在 INPUT 元素中没有。我假设这是因为服务器控件正确地转义了撇号。为了解决这个问题,我尝试将 XML 中的描述节点更改为以下内容:

<Description>This is section &#39;A&#39;</Description>

同样,它在 asp:TextBox 中正确显示,但在 INPUT 元素中却没有。

我的下一个尝试是将节点的值包装在 CDATA 中:

<Description><![CDATA[This is section &#39;A&#39;]]></Description>

最后它在 INPUT 元素中正确显示,但现在 asp:TextBox 显示了两个“ 9;”。我什至试过“& a p o s ;”但结果是一样的。

在可以在服务器控件或 HTML 元素中显示值的 XML 中使用撇号的最佳方法是什么?

【问题讨论】:

    标签: asp.net html xml data-binding


    【解决方案1】:

    使用 '反而。它是 XML 中允许的 5 个实体之一。

    所以你的代码看起来像:

    <Description>This is section &apos;A&apos;</Description>
    

    【讨论】:

    • 我试过了也一样,但是结果和 ' 一样
    • @Bulines 这可能是编码问题。尝试 &apos; (将 & 放在 apos; 前面)看看是否有帮助。
    • 当不在 CDATA 中时,它在 INPUT 中工作正常,但显示“'”在 asp:TextBox.
    【解决方案2】:

    这里的 html 元素的 value 参数有单引号:

     <input type="text" value='<%# XPath("text()") %>' />
    

    这呈现:

    value='This is section 'A'' 
    

    改为使用双引号:

     <input type="text" value="<%# XPath("text()") %>" />
    

    呈现:

    <input type="text" value="This is section 'A'" />
    

    【讨论】:

    • 我不知道为什么我认为 INPUT 元素需要单引号 :)
    猜你喜欢
    • 2011-05-23
    • 2011-01-04
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多