찾다
백엔드 개발XML/RSS 튜토리얼XSLT 구문 - XSLT를 사용하여 .net에서 xml 문서를 변환하기 위한 샘플 코드에 대한 자세한 설명

XSL即可扩展的样式表文件。 可以格式化xml的显示,也可以将xml转换成需要的另一种格式。

学习XSL必须熟悉XPath。XSL和XPath一样简单强大,容易学习。

1. XSL既然可以格式化xml的显示样式,我们先来看如何在xml中引用xsl文件

如下代码示例:

只需在xml文件的文档声明后面添加即可

2. XSL的格式

XSL也是一个标准的xml文件,它以xml文档声明开始,根元素必须是xsl:styleshee,同时根元素必须有version属性指定xsl的版本,和xmlns:xsl=” http://www.php.cn/”指定xsl命名空间,如下示例

3. Xsl要点 如下示例xml


<?xml version="1.0" encoding="utf-8" ?>
<?xml-stylesheet  type="text/xsl" href="pets-templates.xsl"?>
<pets>
  <pig color="blue" weight="100">
    <price>100</price>
    <desc>this is a blue pig</desc>
  </pig>
  <cat color="red" weight="9">
    <price>80</price>
    <desc>this is a red cat</desc>
  </cat>
  <dog color="green" weight="15">
    <price>80</price>
    <desc>this is a green dog</desc>
  </dog>
  <cat color="green" weight="15">
    <price>80</price>
    <desc>this is a green cat</desc>
  </cat>


  <dog color="blue" weight="10">
    <price>100</price>
    <desc>this is a blue dog</desc>
  </dog>
  <dog color="red" weight="9">
    <price>80</price>
    <desc>this is a red dog</desc>
  </dog>
</pets>

上面的xml在通过xsl格式化之后的显示效果如下:

1) xsl:template定义匹配节点的转换模板,属性match=”xpath expression”用来定义模板匹配的元素

如下定义匹配根节点的模板

<xsl:template match=”/”>
</xsl:template>

2) xsl:for-each循环显示select=”xpath expression”选择节点的转换 (类似编程语言中的foreach语句),

如下示例,选择了pets下面的子元素,并循环显示子元素的几点名字:

<xsl:for-each select=”/pets/*”>
<xsl:value-of select=”name()”/>
</xsl:for-each>

3) xsl:if 元素条件显示节点(类似编程语言中的if语句)注意小于号大于号要分别用67bffed8d39c986beaddeed3e8cd5568替代

<xsl:if test=”@weight < 10”>
<i>its weight is less than 10 km</i>
</xsl:if>

4) xsl:choose 多分支条件显示 (类似编程语言中的switch语句)

<xsl:choose >
 <xsl:when test=”name() = ‘pig’”>
<i>this is a pig</i>
 </xsl:when>
<xsl:otherwise>
  <i>this is not a pig</i>
</xsl:otherwise>
</xsl:choose>

5) xsl:value-of 显示选择节点或者属性的值

选择子节点price

<xsl:value-of select=”pets/*/price”/>

选择属性weight

<xsl:value-of select=”pets/*/@weight”/>

6) xsl:attribute 构造xml节点的属性

用来向节点添加属性,例如:

<font>
<xsl:attribute name=”color”><xsl:value-of select=”pets/*/@color”/></xsl:attribute>
</font>

将输出

7) xsl:apply-templates 应用模板

 如果xml文件结构比较复杂,可以定义多个template,然后使用标签应用模板,xsl:apply-templates 可以指定属性select=”xpath”来选择应用的模板,或者不指定select表示选择当前节点的模板。

 请看下面示例xslt文件pets-templates.xsl

完整的示例xsl文件:pets.xsl


<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <head>
        <META http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>lovely pets</title>
        <style type="text/css">
          ul{margin:10px 0 10px 0;padding:0;width:400px;text-align:left;}
          li{height:60px;display:block;list-style:none;padding:4px;border:1px solid #f0f0f0;margin:5px;}
        </style>
      </head>
      <body>
        <center>
        <h1 id="lovely-nbsp-pets">lovely pets</h1>
        <ul>
          <xsl:for-each select="pets/*">
            <li>
              <img  align="right" alt="XSLT 구문 - XSLT를 사용하여 .net에서 xml 문서를 변환하기 위한 샘플 코드에 대한 자세한 설명" >
                <xsl:choose>
                  <xsl:when test="name() = &#39;dog&#39;">
                    <xsl:attribute name="src">http://www.php.cn/;/xsl:attribute>
                  </xsl:when>
                  <xsl:when test="name() = &#39;pig&#39;">
                    <xsl:attribute name="src">http://www.php.cn/;/xsl:attribute>
                  </xsl:when>
                  <xsl:otherwise>
                    <xsl:attribute name="src">http://www.php.cn/@N00.jpg?1143660418</xsl:attribute>
                  </xsl:otherwise>
                </xsl:choose>
              </img>
              <font>
                <xsl:attribute name="face">Courier</xsl:attribute>
                <xsl:attribute name="color">
                  <xsl:value-of select="@color"/>
                </xsl:attribute>
                <xsl:value-of select="name()"/>
              </font> said: "<xsl:value-of select="desc"/>"
              weight:<xsl:value-of select="@weight"/>

              <xsl:if test="@weight < 10">
                <p>
                  <i>its weight is less than 10 km</i>
                </p>
              </xsl:if>


            </li>
          </xsl:for-each>
        </ul>
        </center>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

完整示例文件 pets-templates.xsl:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <head>
        <META http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>lovely pets</title>
        <style type="text/css">
          ul{margin:10px 0 10px 0;padding:0;width:400px;text-align:left;}
          li{height:60px;display:block;list-style:none;padding:4px;border:1px solid #f0f0f0;margin:5px;}
        </style>
      </head>
      <body>
        <center>
          <h1 id="lovely-nbsp-pets">lovely pets</h1>
          <ul>
            <xsl:apply-templates select="pets" />
          </ul>
        </center>
      </body>
    </html>
  </xsl:template>

  <xsl:template match="pets">    
    <xsl:apply-templates select="dog"></xsl:apply-templates>
    <xsl:apply-templates select="pig"></xsl:apply-templates>
    <xsl:apply-templates select="cat"></xsl:apply-templates>
  </xsl:template>

  <xsl:template match="dog">
    <xsl:for-each select=".">
      <li>
        <img  align="right" alt="XSLT 구문 - XSLT를 사용하여 .net에서 xml 문서를 변환하기 위한 샘플 코드에 대한 자세한 설명" >
          <xsl:attribute name="src">http://www.php.cn/;/xsl:attribute>          
        </img>
        <font>
          <xsl:attribute name="face">Courier</xsl:attribute>
          <xsl:attribute name="color">
            <xsl:value-of select="@color"/>
          </xsl:attribute>
          dog
        </font> said: "<xsl:value-of select="desc"/>"
        weight:<xsl:value-of select="@weight"/>

        <xsl:if test="@weight < 10">
          <p>
            <i>its weight is less than 10 km</i>
          </p>
        </xsl:if>
      </li>
    </xsl:for-each>
  </xsl:template>



  <xsl:template match="pig">
    <xsl:for-each select=".">
      <li>
        <img  align="right" alt="XSLT 구문 - XSLT를 사용하여 .net에서 xml 문서를 변환하기 위한 샘플 코드에 대한 자세한 설명" >
          <xsl:attribute name="src">http://www.php.cn/;/xsl:attribute>
        </img>
        <font>
          <xsl:attribute name="face">Courier</xsl:attribute>
          <xsl:attribute name="color">
            <xsl:value-of select="@color"/>
          </xsl:attribute>
          pig
        </font> said: "<xsl:value-of select="desc"/>"
        weight:<xsl:value-of select="@weight"/>

        <xsl:if test="@weight < 10">
          <p>
            <i>its weight is less than 10 km</i>
          </p>
        </xsl:if>
      </li>
    </xsl:for-each>
  </xsl:template>


  <xsl:template match="cat">
    <xsl:for-each select=".">
      <li>
        <img  align="right" alt="XSLT 구문 - XSLT를 사용하여 .net에서 xml 문서를 변환하기 위한 샘플 코드에 대한 자세한 설명" >
          <xsl:attribute name="src">http://www.php.cn/@N00.jpg?1143660418</xsl:attribute>
        </img>
        <font>
          <xsl:attribute name="face">Courier</xsl:attribute>
          <xsl:attribute name="color">
            <xsl:value-of select="@color"/>
          </xsl:attribute>
          cat
        </font> said: "<xsl:value-of select="desc"/>"
        weight:<xsl:value-of select="@weight"/>

        <xsl:if test="@weight < 10">
          <p>
            <i>its weight is less than 10 km</i>
          </p>
        </xsl:if>
      </li>
    </xsl:for-each>
  </xsl:template>
  
</xsl:stylesheet>

在c#.net中使用XslCompiledTransform转换xml文档,XslTransform也可以使用,但是这个类已经被微软标记为过时,最好不要再用了,如下代码示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace UseXslt
{
    class Program
    {
        static void Main(string[] args)
        {
            //声明XslTransform类实例
            System.Xml.Xsl.XslCompiledTransform trans = new System.Xml.Xsl.XslCompiledTransform();

            string xsltFile = @"X:\about.net\System.Xml\example\pets.xsl";
            using (StreamReader rdr = new StreamReader(xsltFile))
            {
                using (XmlReader xmlRdr = XmlReader.Create(rdr))
                {
                    //载入xsl文件
                    trans.Load(xmlRdr);
                }
            }
            string inputFile = @"X:\about.net\System.Xml\example\pets.xml";
            string outputFile = @"X:\about.net\System.Xml\example\pets-out.htm";
            //转化源文件输出到输出文件outputFile
            trans.Transform(inputFile, outputFile);
        }
    }
}


有一点需要注意,使用XslCompiledTransform转换出来的文件,是一个html格式的,这个类会自动在html的head标签中添加一个未关闭的meta标签 ;微软帮我们想的太多了。

Xslt还可以指定参数,定义变量,有关这些方面请查看相关文档。


위 내용은 XSLT 구문 - XSLT를 사용하여 .net에서 xml 문서를 변환하기 위한 샘플 코드에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
XML의 RSS : 태그, 속성 및 구조 디코딩XML의 RSS : 태그, 속성 및 구조 디코딩Apr 24, 2025 am 12:09 AM

RSS는 컨텐츠를 게시하고 구독하는 데 사용되는 XML 기반 형식입니다. RSS 파일의 XML 구조에는 컨텐츠 항목을 나타내는 루트 요소, 요소 및 여러 요소가 포함됩니다. XML Parser를 통해 RSS 파일을 읽고 구문 분석하고 사용자는 최신 컨텐츠를 구독하고 얻을 수 있습니다.

RSS에서 XML의 장점 : 기술 깊은 다이빙RSS에서 XML의 장점 : 기술 깊은 다이빙Apr 23, 2025 am 12:02 AM

XML은 RSS에서 구조화 된 데이터, 확장 성, 크로스 플랫폼 호환성 및 구문 분석 검증의 장점을 가지고 있습니다. 1) 구조화 된 데이터는 컨텐츠의 일관성과 신뢰성을 보장합니다. 2) 확장 성은 콘텐츠 요구에 맞게 맞춤형 태그를 추가 할 수 있습니다. 3) 크로스 플랫폼 호환성은 다른 장치에서 원활하게 작동합니다. 4) 분석 및 검증 도구는 피드의 품질과 무결성을 보장합니다.

XML의 RSS : 컨텐츠 신디케이션의 핵심을 공개합니다XML의 RSS : 컨텐츠 신디케이션의 핵심을 공개합니다Apr 22, 2025 am 12:08 AM

XML에서 RSS 구현은 구조화 된 XML 형식을 통해 컨텐츠를 구성하는 것입니다. 1) RSS는 채널 정보 및 프로젝트 목록과 같은 요소를 포함하여 XML을 데이터 교환 형식으로 사용합니다. 2) RSS 파일을 생성 할 때는 사양에 따라 컨텐츠를 구성하고 구독을 위해 서버에 게시해야합니다. 3) RSS 파일은 리더 또는 플러그인을 통해 구독하여 컨텐츠를 자동으로 업데이트 할 수 있습니다.

기본 사항을 넘어서 : 고급 RSS 문서 기능기본 사항을 넘어서 : 고급 RSS 문서 기능Apr 21, 2025 am 12:03 AM

RSS의 고급 기능에는 컨텐츠 네임 스페이스, 확장 모듈 및 조건부 구독이 포함됩니다. 1) 컨텐츠 네임 스페이스는 RSS 기능을 확장합니다. 2) 메타 데이터를 추가하기 위해 Dublincore 또는 iTunes와 같은 확장 된 모듈, 3) 특정 조건에 따라 조건부 구독 필터 항목. 이러한 기능은 XML 요소 및 속성을 추가하여 정보 수집 효율성을 향상시켜 구현됩니다.

XML 백본 : RSS 피드가 구조화되는 방법XML 백본 : RSS 피드가 구조화되는 방법Apr 20, 2025 am 12:02 AM

rssfeedsusexmltostructurecontentupdates.1) xmlprovideahierarchicalstructurefordata.2) the ElementDefinesThefeed 'sidentityandContainsElements.3) elementsreent indindividualcontentpieces.4) rssisextensible, 허용 Bestpracticesin

RSS & XML : 웹 컨텐츠의 동적 듀오 이해RSS & XML : 웹 컨텐츠의 동적 듀오 이해Apr 19, 2025 am 12:03 AM

RSS 및 XML은 웹 컨텐츠 관리를위한 도구입니다. RSS는 컨텐츠를 게시하고 구독하는 데 사용되며 XML은 데이터를 저장하고 전송하는 데 사용됩니다. 컨텐츠 게시, 구독 및 업데이트 푸시와 함께 작동합니다. 사용의 예로는 RSS 게시 블로그 게시물 및 XML 저장 도서 정보가 있습니다.

RSS 문서 : 웹 신디케이션의 기초RSS 문서 : 웹 신디케이션의 기초Apr 18, 2025 am 12:04 AM

RSS 문서는 자주 업데이트되는 콘텐츠를 게시하고 구독하는 데 사용되는 XML 기반 구조 파일입니다. 주요 기능에는 1) 자동화 된 컨텐츠 업데이트, 2) 컨텐츠 집계 및 3) 브라우징 효율 향상이 포함됩니다. RSSFEED를 통해 사용자는 적시에 다른 소스에서 최신 정보를 구독하고 얻을 수 있습니다.

RSS 디코딩 : 컨텐츠 피드의 XML 구조RSS 디코딩 : 컨텐츠 피드의 XML 구조Apr 17, 2025 am 12:09 AM

RSS의 XML 구조에는 다음이 포함됩니다. 1. XML 선언 및 RSS 버전, 2. 채널 (채널), 3. 항목. 이러한 부분은 RSS 파일의 기초를 형성하여 사용자가 XML 데이터를 구문 분석하여 컨텐츠 정보를 얻고 처리 할 수 ​​있도록합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는