Отобразить XML на странице ASP.NET

У меня есть строка, содержащая XML-документ с использованием LinqtoXML

Каков наилучший способ отображения на странице asp.net, как есть.

Ответы

Ответ 1

Мне хотелось бы сделать это так, как сказал Деннис (используя элемент управления <asp:Xml>). Но это требует использования таблицы стилей XSL для форматирования XML. Элемент управления Xml не позволяет передавать кодированную HTML-строку в качестве свойства DocumentContent и не предоставляет какой-либо метод для кодирования содержимого.

Как я уже упоминал в комментарии к сообщению Дениса, файл defaultss.xsl, содержащийся в msxml.dll, недоступен публично (и не соответствует XSL 1.0). Однако публичная конвертированная версия была размещена здесь: http://www.dpawson.co.uk/xsl/sect2/microsoft.html#d7615e227. Я тестировал его, и он работает, хотя и немного глючит.

Поэтому я думаю, что самым простым способом было бы использовать элемент управления <asp:Literal> для вывода предварительно кодированного XML на страницу. Следующий пример демонстрирует этот метод:


<%@ Page Language="C#" %>

<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>

<script runat="server">
  protected void Page_Load(object sender, EventArgs e)
  {
    string theXML = Server.HtmlEncode(File.ReadAllText(Server.MapPath("~/XML/myxmlfile.xml")));
    lit1.Text = theXML;
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Untitled Page</title>
</head>
<body>
  <form id="form1" runat="server">
    <div>
      <pre>
        <asp:Literal ID="lit1" runat="server" />
      </pre>
    </div>
  </form>
</body>
</html>

Ответ 2

Используйте элемент управления asp:Xml вместе с этим Таблица стилей по умолчанию как TransformSource. Это даст вам представление, очень похожее на то, что вы видите, когда вы открываете xml файл в Internet Explorer в комплекте с подсветкой синтаксиса и цветом.

Я удалил расширяющуюся/сворачивающуюся функциональность node, потому что я не мог заставить ее работать. Этот файл является xsl 1.0 и отлично работает без ошибок для моих целей.

Чтобы избежать любых будущих проблем с моим связанным файлом, вот содержание:

<!--
|
| XSLT REC Compliant Version of IE5 Default Stylesheet
|
| Original version by Jonathan Marsh ([email protected])
| http://msdn.microsoft.com/xml/samples/defaultss/defaultss.xsl
|
| Conversion to XSLT 1.0 REC Syntax by Steve Muench ([email protected])
|
+-->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="no" method="html"/>
<xsl:template match="/">
    <xsl:apply-templates/>
</xsl:template>
<xsl:template match="processing-instruction()">
    <DIV class="e">
        <SPAN class="b">
            <xsl:call-template name="entity-ref">
                <xsl:with-param name="name">nbsp</xsl:with-param>
            </xsl:call-template>
        </SPAN>
        <SPAN class="m">
            <xsl:text>&lt;?</xsl:text>
        </SPAN>
        <SPAN class="pi">
            <xsl:value-of select="name(.)"/>
            <xsl:value-of select="."/>
        </SPAN>
        <SPAN class="m">
            <xsl:text>?></xsl:text>
        </SPAN>
    </DIV>
</xsl:template>
<xsl:template match="processing-instruction('xml')">
    <DIV class="e">
        <SPAN class="b">
            <xsl:call-template name="entity-ref">
                <xsl:with-param name="name">nbsp</xsl:with-param>
            </xsl:call-template>
        </SPAN>
        <SPAN class="m">
            <xsl:text>&lt;?</xsl:text>
        </SPAN>
        <SPAN class="pi">
            <xsl:text>xml </xsl:text>
            <xsl:for-each select="@*">
                <xsl:value-of select="name(.)"/>
                <xsl:text>="</xsl:text>
                <xsl:value-of select="."/>
                <xsl:text>" </xsl:text>
            </xsl:for-each>
        </SPAN>
        <SPAN class="m">
            <xsl:text>?></xsl:text>
        </SPAN>
    </DIV>
</xsl:template>
<xsl:template match="@*">
    <SPAN>
        <xsl:attribute name="class"><xsl:if test="xsl:*/@*"><xsl:text>x</xsl:text></xsl:if><xsl:text>t</xsl:text></xsl:attribute>
        <xsl:value-of select="name(.)"/>
    </SPAN>
    <SPAN class="m">="</SPAN>
    <B>
        <xsl:value-of select="."/>
    </B>
    <SPAN class="m">"</SPAN>
</xsl:template>
<xsl:template match="text()">
    <DIV class="e">
        <SPAN class="b"> </SPAN>
        <SPAN class="tx">
            <xsl:value-of select="."/>
        </SPAN>
    </DIV>
</xsl:template>
<xsl:template match="comment()">
    <DIV class="k">
        <SPAN>
            <!--<A STYLE="visibility:hidden" class="b" onclick="return false" onfocus="h()">-</A>-->
            <SPAN class="m">
                <xsl:text>&lt;!--</xsl:text>
            </SPAN>
        </SPAN>
        <SPAN class="ci" id="clean">
            <PRE>
                <xsl:value-of select="."/>
            </PRE>
        </SPAN>
        <SPAN class="b">
            <xsl:call-template name="entity-ref">
                <xsl:with-param name="name">nbsp</xsl:with-param>
            </xsl:call-template>
        </SPAN>
        <SPAN class="m">
            <xsl:text>--></xsl:text>
        </SPAN>
        <SCRIPT>f(clean);</SCRIPT>
    </DIV>
</xsl:template>
<xsl:template match="*">
    <DIV class="e">
        <DIV STYLE="margin-left:1em;text-indent:-2em">
            <SPAN class="b">
                <xsl:call-template name="entity-ref">
                    <xsl:with-param name="name">nbsp</xsl:with-param>
                </xsl:call-template>
            </SPAN>
            <SPAN class="m">&lt;</SPAN>
            <SPAN>
                <xsl:attribute name="class"><xsl:if test="xsl:*"><xsl:text>x</xsl:text></xsl:if><xsl:text>t</xsl:text></xsl:attribute>
                <xsl:value-of select="name(.)"/>
                <xsl:if test="@*">
                    <xsl:text> </xsl:text>
                </xsl:if>
            </SPAN>
            <xsl:apply-templates select="@*"/>
            <SPAN class="m">
                <xsl:text>/></xsl:text>
            </SPAN>
        </DIV>
    </DIV>
</xsl:template>
<xsl:template match="*[node()]">
    <DIV class="e">
        <DIV class="c">
            <!--<A class="b" href="#" onclick="return false" onfocus="h()">-</A>-->
            <SPAN class="m">&lt;</SPAN>
            <SPAN>
                <xsl:attribute name="class"><xsl:if test="xsl:*"><xsl:text>x</xsl:text></xsl:if><xsl:text>t</xsl:text></xsl:attribute>
                <xsl:value-of select="name(.)"/>
                <xsl:if test="@*">
                    <xsl:text> </xsl:text>
                </xsl:if>
            </SPAN>
            <xsl:apply-templates select="@*"/>
            <SPAN class="m">
                <xsl:text>></xsl:text>
            </SPAN>
        </DIV>
        <DIV>
            <xsl:apply-templates/>
            <DIV>
                <SPAN class="b">
                    <xsl:call-template name="entity-ref">
                        <xsl:with-param name="name">nbsp</xsl:with-param>
                    </xsl:call-template>
                </SPAN>
                <SPAN class="m">
                    <xsl:text>&lt;/</xsl:text>
                </SPAN>
                <SPAN>
                    <xsl:attribute name="class"><xsl:if test="xsl:*"><xsl:text>x</xsl:text></xsl:if><xsl:text>t</xsl:text></xsl:attribute>
                    <xsl:value-of select="name(.)"/>
                </SPAN>
                <SPAN class="m">
                    <xsl:text>></xsl:text>
                </SPAN>
            </DIV>
        </DIV>
    </DIV>
</xsl:template>
<xsl:template match="*[text() and not (comment() or processing-instruction())]">
    <DIV class="e">
        <DIV STYLE="margin-left:1em;text-indent:-2em">
            <SPAN class="b">
                <xsl:call-template name="entity-ref">
                    <xsl:with-param name="name">nbsp</xsl:with-param>
                </xsl:call-template>
            </SPAN>
            <SPAN class="m">
                <xsl:text>&lt;</xsl:text>
            </SPAN>
            <SPAN>
                <xsl:attribute name="class"><xsl:if test="xsl:*"><xsl:text>x</xsl:text></xsl:if><xsl:text>t</xsl:text></xsl:attribute>
                <xsl:value-of select="name(.)"/>
                <xsl:if test="@*">
                    <xsl:text> </xsl:text>
                </xsl:if>
            </SPAN>
            <xsl:apply-templates select="@*"/>
            <SPAN class="m">
                <xsl:text>></xsl:text>
            </SPAN>
            <SPAN class="tx">
                <xsl:value-of select="."/>
            </SPAN>
            <SPAN class="m">&lt;/</SPAN>
            <SPAN>
                <xsl:attribute name="class"><xsl:if test="xsl:*"><xsl:text>x</xsl:text></xsl:if><xsl:text>t</xsl:text></xsl:attribute>
                <xsl:value-of select="name(.)"/>
            </SPAN>
            <SPAN class="m">
                <xsl:text>></xsl:text>
            </SPAN>
        </DIV>
    </DIV>
</xsl:template>
<xsl:template match="*[*]" priority="20">
    <DIV class="e">
        <DIV STYLE="margin-left:1em;text-indent:-2em" class="c">
            <!--<A class="b" href="#" onclick="return false" onfocus="h()">-</A>-->
            <SPAN class="m">&lt;</SPAN>
            <SPAN>
                <xsl:attribute name="class"><xsl:if test="xsl:*"><xsl:text>x</xsl:text></xsl:if><xsl:text>t</xsl:text></xsl:attribute>
                <xsl:value-of select="name(.)"/>
                <xsl:if test="@*">
                    <xsl:text> </xsl:text>
                </xsl:if>
            </SPAN>
            <xsl:apply-templates select="@*"/>
            <SPAN class="m">
                <xsl:text>></xsl:text>
            </SPAN>
        </DIV>
        <DIV>
            <xsl:apply-templates/>
            <DIV>
                <SPAN class="b">
                    <xsl:call-template name="entity-ref">
                        <xsl:with-param name="name">nbsp</xsl:with-param>
                    </xsl:call-template>
                </SPAN>
                <SPAN class="m">
                    <xsl:text>&lt;/</xsl:text>
                </SPAN>
                <SPAN>
                    <xsl:attribute name="class"><xsl:if test="xsl:*"><xsl:text>x</xsl:text></xsl:if><xsl:text>t</xsl:text></xsl:attribute>
                    <xsl:value-of select="name(.)"/>
                </SPAN>
                <SPAN class="m">
                    <xsl:text>></xsl:text>
                </SPAN>
            </DIV>
        </DIV>
    </DIV>
</xsl:template>
<xsl:template name="entity-ref">
    <xsl:param name="name"/>
    <xsl:text disable-output-escaping="yes">&amp;</xsl:text>
    <xsl:value-of select="$name"/>
    <xsl:text>;</xsl:text>
</xsl:template>
</xsl:stylesheet>

Ответ 3

С# решение Это сработало для меня:

string encodedXml = String.Format("<pre>{0}</pre>", HttpUtility.HtmlEncode(xmlStr));
testLb.Text = encodedXml;

Ответ 4

HTML PRE теги в div и просто эхо из строки, которая правильно экранирована?

Div дает вам выравнивание/форматирование, в то время как PRE должен сохранять пробелы

Ответ 5

Отображение XML-форматированного кода без использования элемента управления XML

Вот решение VB.NET:

Public Shared Function FormatXml(ByVal xmlDoc As XmlDocument) As String  
    Dim sb As New StringBuilder()  
    `'We will use stringWriter to push the formated xml into our StringBuilder sb.`  
    Using stringWriter As New StringWriter(sb)  
        `'We will use the Formatting of our xmlTextWriter to provide our indentation.`  
        Using xmlTextWriter As New XmlTextWriter(stringWriter)  
            xmlTextWriter.Formatting = Formatting.Indented  
            xmlDoc.WriteTo(xmlTextWriter)  
        End Using
    End Using
    Return sb.ToString()
End Function

Используйте эту функцию для установки текста многострочного текстового поля или метки:

XmlViewTextBox.Text = FormatXml(xmlDoc)

Если вы пытаетесь использовать XML-строку, сначала конвертируйте ее в XmlDocument:

Dim xmlDoc As New XmlDocument
xmlDoc.LoadXml(xmlString)

Это решение будет отображать XML-код на странице HTML при сохранении разрывов строк и отступов.