日期:2014-05-17  浏览次数:20671 次

新时尚Windows8开发(31):去掉文本中的HTML标记

告诉EveryBody一个好消息,去掉字符串中的HTML标记,再也不用写正则表达式了,你知道吗?一行代码就够了!

事不宜迟,来吧,动手。

 

1、新建“板砖”应用程序项目。

2、在界面中放一个TextBox,用来输入带HTML的文本,一个Button,点击后转换,一个TextBlock,显示转换后的字符串。XAML如下:

<Page
    x:Class="App1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBox x:Name="txtInput" Grid.Row="0" TextWrapping="Wrap"/>
        <Button Grid.Row="1" Margin="5,12,0,13" Content="转换" Click="onClick"/>
        <ScrollViewer Grid.Row="2" VerticalScrollBarVisibility="Visible" HorizontalScrollMode="Enabled">
            <TextBlock x:Name="tbResult" FontSize="24" TextWrapping="Wrap"/>
        </ScrollViewer>
    </Grid>
</Page>


3、而后我们在代码中处理Click事件。记得先引入Windows.Data.Html命名空间。

        private void onClick(object sender, RoutedEventArgs e)
        {
            this.tbResult.Text = HtmlUtilities.ConvertToText(this.txtInput.Text);
        }


 

然后,你就试试看。