XMLpracticalapplicationcase

LearningXML in practicalprojectin application, UnderstandXML in configurationfile, data交换, Webservice, RSS feedetc.场景in 具体usingmethod and best practices

XMLpracticalapplicationoverview

XMLserving as一种common data交换格式, in 现代计算机systemin has 着广泛 application. 它 平台无关性, 自我describes性 and 良 good readable 性使其成 for 不同system之间data交换 理想选择. 以 under is XML in practicalprojectin 一些commonapplication场景:

  • configurationfile: 许 many application程序usingXMLserving asconfigurationfile格式, such asWebserver, applicationserver, datalibraryetc.
  • data交换: in 不同system, 平台 and programminglanguage之间交换data
  • Webservice: such asSOAP and RESTful Webservice, usingXMLformatrequest and responsedata
  • RSS and Atom: 用于release and subscribe new 闻, 博客 and other in 容
  • documentation标记: such asDocBook, XHTMLetc., 用于structure化documentation creation and processing
  • datastore: 用于storestructure化data, such asconfigurationinformation, 元dataetc.
  • message传递: in distributedsystemin传递message, such asJMS, AMQPetc.

XMLconfigurationfile

XML常被用作application程序 configurationfile格式, 因 for 它具 has 良 good readable 性 and structure化features. 许 many 流行 软件 and framework都usingXMLserving asconfigurationfile格式.

1. Webserverconfiguration

Apache and Nginxetc.WebserverusingXML or class似XML 格式来configuration虚拟主机, proxy规则, security设置etc..

Tomcatserverconfigurationexample
<?xml version='1.0' encoding='utf-8'?>
<Server port="8005" shutdown="SHUTDOWN">
  <Service name="Catalina">
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
    <Engine name="Catalina" defaultHost="localhost">
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autodeployment="true">
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t "%r" %s %b" />
      </Host>
    </Engine>
  </Service>
</Server>

2. Springframeworkconfiguration

SpringframeworkusingXMLconfigurationfile来定义Bean, 依赖注入 and AOPetc..

Springconfigurationfileexample
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd">
    
    <!-- 启用注解扫描 -->
    <context:component-scan base-package="com.example" />
    
    <!-- configurationdatasources -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test" />
        <property name="username" value="root" />
        <property name="password" value="password" />
    </bean>
    
    <!-- configurationtransactionmanagement器 -->
    <bean id="transactionmanagementr" class="org.springframework.jdbc.datasource.DataSourceTransactionmanagementr">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <!-- 启用transaction注解 -->
    <tx:annotation-driven transaction-manager="transactionmanagementr" />
    
</beans>

XMLdata交换

XML is 不同system之间data交换 常用格式, 尤其 is in 异构systemin. 它可以表示 complex datastructure, 并且易于解析 and 生成.

1. Webservicedata交换

SOAP (Simple Object Access Protocol) WebserviceusingXML来formatrequest and responsedata.

SOAPrequestexample
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
               xmlns:ser="http://www.example.com/webservice">
   <soap:Header/>
   <soap:Body>
      <ser:GetWeatherRequest>
         <ser:City>北京</ser:City>
         <ser:Date>2025-01-15</ser:Date>
      </ser:GetWeatherRequest>
   </soap:Body>
</soap:Envelope>
SOAPresponseexample
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
               xmlns:ser="http://www.example.com/webservice">
   <soap:Header/>
   <soap:Body>
      <ser:GetWeatherResponse>
         <ser:WeatherInfo>
            <ser:City>北京</ser:City>
            <ser:Date>2025-01-15</ser:Date>
            <ser:Temperature>-5°C ~ 5°C</ser:Temperature>
            <ser:Condition>晴</ser:Condition>
            <ser:Humidity>45%</ser:Humidity>
         </ser:WeatherInfo>
      </ser:GetWeatherResponse>
   </soap:Body>
</soap:Envelope>

2. dataimportexport

许 many application程序supportusingXML格式import and exportdata, such as办公软件, CRMsystem, CMSsystemetc..

联系人dataXMLexample
<?xml version="1.0" encoding="UTF-8"?>
<contacts>
    <contact id="1">
        <name>
            <first>张</first>
            <last>三</last>
        </name>
        <email>zhangsan@example.com</email>
        <phone type="mobile">13800138000</phone>
        <address>
            <street>in关村 big 街1号</street>
            <city>北京</city>
            <zipcode>100080</zipcode>
            <country>in国</country>
        </address>
    </contact>
    <contact id="2">
        <name>
            <first>李</first>
            <last>四</last>
        </name>
        <email>lisi@example.com</email>
        <phone type="mobile">13900139000</phone>
        <phone type="work">010-12345678</phone>
        <address>
            <street>人民 big 道1号</street>
            <city> on 海</city>
            <zipcode>200000</zipcode>
            <country>in国</country>
        </address>
    </contact>
</contacts>

XML in 容release

XML常用于 in 容release and subscribe, such asRSS (Really Simple Syndication) and Atom格式.

1. RSS Feed

RSS is a用于release经常update in 容 格式, such as博客文章, new 闻, 音频 and 视频etc..

RSS Feedexample
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>techniques博客</title>
    <link>http://www.example.com/blog</link>
    <atom:link href="http://www.example.com/blog/rss.xml" rel="self" type="application/rss+xml" />
    <description>分享techniquesknowledge and experience</description>
    <language>zh-CN</language>
    <pubDate>Wed, 15 Jan 2025 10:30:00 +0800</pubDate>
    <lastbuildDate>Wed, 15 Jan 2025 10:30:00 +0800</lastbuildDate>
    <generator>WordPress 6.4</generator>
    
    <item>
      <title>XMLBasicstutorial</title>
      <link>http://www.example.com/blog/xml-basics</link>
      <comments>http://www.example.com/blog/xml-basics#comments</comments>
      <pubDate>Wed, 15 Jan 2025 09:00:00 +0800</pubDate>
      <category><![CDATA[XML]]></category>
      <guid isPermaLink="false">http://www.example.com/blog/?p=1</guid>
      <description><![CDATA[LearningXML basicconcepts, 语法 and application. ]]></description>
      <content:encoded><![CDATA[<p>XML is a可scale标记language, 用于store and 传输data. 本文将介绍XML basicconcepts, 语法规则 and commonapplication. </p>]]></content:encoded>
    </item>
    
    <item>
      <title>XSLT转换techniques</title>
      <link>http://www.example.com/blog/xslt-transformations</link>
      <comments>http://www.example.com/blog/xslt-transformations#comments</comments>
      <pubDate>Tue, 14 Jan 2025 14:30:00 +0800</pubDate>
      <category><![CDATA[XSLT]]></category>
      <guid isPermaLink="false">http://www.example.com/blog/?p=2</guid>
      <description><![CDATA[深入UnderstandXSLT转换techniques, implementationXMLdata flexibleprocessing. ]]></description>
      <content:encoded><![CDATA[<p>XSLT is a用于将XMLdocumentation转换 for other格式 language. 本文将介绍XSLT basic原理, 语法 and applicationexample. </p>]]></content:encoded>
    </item>
  </channel>
</rss>

XMLmessage传递

in distributedsystemin, XML常用于message传递, such asJMS (Java Message Service) and AMQP (advanced Message Queuing Protocol) etc.messagein间件.

JMSmessageXMLexample
<?xml version="1.0" encoding="UTF-8"?>
<orderMessage>
    <messageHeader>
        <messageId>MSG-20250115-001</messageId>
        <messageType>ORDER_CREATE</messageType>
        <timestamp>2025-01-15T10:30:00+08:00</timestamp>
        <sender>order-service</sender>
        <receiver>payment-service</receiver>
    </messageHeader>
    <messageBody>
        <order>
            <orderId>ORD-20250115-001</orderId>
            <customerId>CUST-001</customerId>
            <orderDate>2025-01-15T10:25:00+08:00</orderDate>
            <totalAmount>199.00</totalAmount>
            <currency>CNY</currency>
            <items>
                <item>
                    <productId>PROD-001</productId>
                    <productName>XMLBasicstutorial</productName>
                    <quantity>1</quantity>
                    <unitPrice>99.00</unitPrice>
                </item>
                <item>
                    <productId>PROD-002</productId>
                    <productName>XSLT转换techniques</productName>
                    <quantity>1</quantity>
                    <unitPrice>89.00</unitPrice>
                </item>
            </items>
            <paymentInfo>
                <paymentMethod>ALIPAY</paymentMethod>
                <paymentStatus>PENDING</paymentStatus>
            </paymentInfo>
        </order>
    </messageBody>
</orderMessage>

XMLdocumentation标记

XML常用于structure化documentation 标记, such asDocBook, XHTML, SVGetc..

1. SVG (Scalable Vector Graphics)

SVG is a用于describes二维矢量graph形 XML格式.

SVGgraph形example
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300">
    <!-- 背景矩形 -->
    <rect width="400" height="300" fill="#f0f0f0" />
    
    <!-- 标题文本 -->
    <text x="200" y="30" font-family="Arial" font-size="24" fill="#4285F4" text-anchor="middle">XMLapplicationexample</text>
    
    <!-- 圆形 -->
    <circle cx="100" cy="150" r="50" fill="#34A853" stroke="#2d8f48" stroke-width="2" />
    <text x="100" y="155" font-family="Arial" font-size="14" fill="white" text-anchor="middle">configurationfile</text>
    
    <!-- 矩形 -->
    <rect x="180" y="100" width="100" height="100" fill="#FBBC05" stroke="#f9ab00" stroke-width="2" />
    <text x="230" y="155" font-family="Arial" font-size="14" fill="white" text-anchor="middle">data交换</text>
    
    <!--  many edge形 -->
    <polygon points="350,150 300,100 300,200" fill="#EA4335" stroke="#d93025" stroke-width="2" />
    <text x="325" y="155" font-family="Arial" font-size="14" fill="white" text-anchor="middle">Webservice</text>
    
    <!-- 连接线 -->
    <line x1="150" y1="150" x2="180" y2="150" stroke="#555" stroke-width="2" />
    <line x1="280" y1="150" x2="300" y2="150" stroke="#555" stroke-width="2" />
</svg>

2. XHTML (Extensible Hypertext Markup Language)

XHTML is HTML XMLversion, 它将HTML标记language and XML 严格语法结合起来.

XHTMLdocumentationexample
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>XHTMLexample</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
    <div id="header">
        <h1>网站标题</h1>
        <ul id="nav">
            <li><a href="index.html">首页</a></li>
            <li><a href="about.html">About Us</a></li>
            <li><a href="contact.html">Contact Us</a></li>
        </ul>
    </div>
    <div id="content">
        <h2>文章标题</h2>
        <p>这 is 一篇XHTML格式 文章example. </p>
        <img src="image.jpg" alt="graph片example" width="300" height="200" />
    </div>
    <div id="footer">
        <p>© 2025 网站名称. All rights reserved.</p>
    </div>
</body>
</html>

实践case: usingXMLimplementationconfigurationmanagementsystem

casedescribes

creation一个 simple configurationmanagementsystem, usingXMLstore and managementapplication程序 configurationinformation. system应该able toimplementation以 under functions:

  • 加载XMLconfigurationfile
  • 读取configurationparameter
  • modifyconfigurationparameter
  • 保存configurationfile
  • verificationconfigurationfile has 效性

implementation步骤

  1. designXMLconfigurationfile structure
  2. creationXML Schema or DTD来verificationconfigurationfile
  3. implementationconfigurationmanagementclass, 用于加载, 读取, modify and 保存configuration
  4. writingtestcodeverificationsystemfunctions

最终code

XMLconfigurationfile: config.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="config.xsl"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="config.xsd">
    <application>
        <name>configurationmanagementsystem</name>
        <version>1.0.0</version>
        <description>用于managementapplication程序configuration system</description>
    </application>
    <database>
        <driver>com.mysql.jdbc.Driver</driver>
        <url>jdbc:mysql://localhost:3306/config_db</url>
        <username>root</username>
        <password>password</password>
        <maxConnections>10</maxConnections>
        <timeout>30</timeout>
    </database>
    <logging>
        <level>INFO</level>
        <file>logs/app.log</file>
        <maxFileSize>10MB</maxFileSize>
        <backupCount>5</backupCount>
    </logging>
    <server>
        <host>localhost</host>
        <port>8080</port>
        <ssl>false</ssl>
        <maxThreads>50</maxThreads>
    </server>
</config>
XML Schema: config.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="config">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="application">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="name" type="xs:string" />
                            <xs:element name="version" type="xs:string" />
                            <xs:element name="description" type="xs:string" />
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="database">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="driver" type="xs:string" />
                            <xs:element name="url" type="xs:string" />
                            <xs:element name="username" type="xs:string" />
                            <xs:element name="password" type="xs:string" />
                            <xs:element name="maxConnections" type="xs:integer" />
                            <xs:element name="timeout" type="xs:integer" />
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="logging">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="level" type="xs:string" />
                            <xs:element name="file" type="xs:string" />
                            <xs:element name="maxFileSize" type="xs:string" />
                            <xs:element name="backupCount" type="xs:integer" />
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="server">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="host" type="xs:string" />
                            <xs:element name="port" type="xs:integer" />
                            <xs:element name="ssl" type="xs:boolean" />
                            <xs:element name="maxThreads" type="xs:integer" />
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>
XSLT样式表: config.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>
                <title>configurationmanagementsystem</title>
                <style>
                    body {
                        font-family: Arial, sans-serif;
                        margin: 20px;
                    }
                    h1 {
                        color: #4285F4;
                    }
                    h2 {
                        color: #34A853;
                        margin-top: 30px;
                    }
                    .config-section {
                        background-color: #f0f0f0;
                        padding: 15px;
                        margin: 10px 0;
                        border-radius: 5px;
                    }
                    .config-item {
                        margin: 10px 0;
                    }
                    .config-label {
                        font-weight: bold;
                        display: inline-block;
                        width: 150px;
                    }
                </style>
            </head>
            <body>
                <h1>configurationmanagementsystem</h1>
                
                <div class="config-section">
                    <h2>application程序information</h2>
                    <div class="config-item">
                        <span class="config-label">名称: </span>
                        <span><xsl:value-of select="config/application/name" /></span>
                    </div>
                    <div class="config-item">
                        <span class="config-label">version: </span>
                        <span><xsl:value-of select="config/application/version" /></span>
                    </div>
                    <div class="config-item">
                        <span class="config-label">describes: </span>
                        <span><xsl:value-of select="config/application/description" /></span>
                    </div>
                </div>
                
                <div class="config-section">
                    <h2>datalibraryconfiguration</h2>
                    <div class="config-item">
                        <span class="config-label">驱动: </span>
                        <span><xsl:value-of select="config/database/driver" /></span>
                    </div>
                    <div class="config-item">
                        <span class="config-label">URL: </span>
                        <span><xsl:value-of select="config/database/url" /></span>
                    </div>
                    <div class="config-item">
                        <span class="config-label">user名: </span>
                        <span><xsl:value-of select="config/database/username" /></span>
                    </div>
                    <div class="config-item">
                        <span class="config-label">password: </span>
                        <span>******</span>
                    </div>
                    <div class="config-item">
                        <span class="config-label">最 big connections: </span>
                        <span><xsl:value-of select="config/database/maxConnections" /></span>
                    </div>
                    <div class="config-item">
                        <span class="config-label">超时时间: </span>
                        <span><xsl:value-of select="config/database/timeout" /></span>
                    </div>
                </div>
                
                <div class="config-section">
                    <h2>logconfiguration</h2>
                    <div class="config-item">
                        <span class="config-label">log级别: </span>
                        <span><xsl:value-of select="config/logging/level" /></span>
                    </div>
                    <div class="config-item">
                        <span class="config-label">logfile: </span>
                        <span><xsl:value-of select="config/logging/file" /></span>
                    </div>
                    <div class="config-item">
                        <span class="config-label">最 big file big  small : </span>
                        <span><xsl:value-of select="config/logging/maxFileSize" /></span>
                    </div>
                    <div class="config-item">
                        <span class="config-label">backup数量: </span>
                        <span><xsl:value-of select="config/logging/backupCount" /></span>
                    </div>
                </div>
                
                <div class="config-section">
                    <h2>serverconfiguration</h2>
                    <div class="config-item">
                        <span class="config-label">主机: </span>
                        <span><xsl:value-of select="config/server/host" /></span>
                    </div>
                    <div class="config-item">
                        <span class="config-label">端口: </span>
                        <span><xsl:value-of select="config/server/port" /></span>
                    </div>
                    <div class="config-item">
                        <span class="config-label">SSL: </span>
                        <span><xsl:value-of select="config/server/ssl" /></span>
                    </div>
                    <div class="config-item">
                        <span class="config-label">最 big thread数: </span>
                        <span><xsl:value-of select="config/server/maxThreads" /></span>
                    </div>
                </div>
            </body>
        </html>
    </xsl:template>
    
</xsl:stylesheet>

互动练习

练习1: designXMLconfigurationfile

for 一个 in 线购物systemdesignXMLconfigurationfile, 要求package含以 under configurationinformation:
  1. systembasicinformation (名称, version, describes)
  2. datalibraryconfiguration (驱动, URL, user名, password, 连接池configuration)
  3. cacheconfiguration (class型, 过期时间, 最 big big small )
  4. 支付configuration (support 支付方式, APIkey)
  5. logconfiguration (级别, filepath, 最 big file big small )

XMLconfigurationfiledesignsuch as under :

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <system>
        <name> in 线购物system</name>
        <version>2.0.0</version>
        <description>一个functions完整  in 线购物平台</description>
        <environment>production</environment>
    </system>
    
    <database>
        <driver>com.mysql.jdbc.Driver</driver>
        <url>jdbc:mysql://localhost:3306/shop_db?useSSL=false&serverTimezone=UTC</url>
        <username>shop_user</username>
        <password>shop_password</password>
        <connectionPool>
            <initialSize>5</initialSize>
            <maxActive>20</maxActive>
            <maxIdle>10</maxIdle>
            <minIdle>3</minIdle>
            <maxWait>30000</maxWait>
        </connectionPool>
    </database>
    
    <cache>
        <type>redis</type>
        <host>localhost</host>
        <port>6379</port>
        <password></password>
        <database>0</database>
        <expiration>3600</expiration>
        <maxSize>10000</maxSize>
    </cache>
    
    <payment>
        <methods>
            <method name="alipay" enabled="true">
                <appId>2021000119656789</appId>
                <privateKey>MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQ...</privateKey>
                <publicKey>MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...</publicKey>
            </method>
            <method name="wechat" enabled="true">
                <appId>wx1234567890abcdef</appId>
                <mchId>1234567890</mchId>
                <apiKey>abcdef1234567890abcdef1234567890</apiKey>
            </method>
            <method name="creditcard" enabled="false">
                <gatewayUrl>https://payment.example.com/creditcard</gatewayUrl>
                <merchantId>MERCHANT-001</merchantId>
            </method>
        </methods>
    </payment>
    
    <logging>
        <level>INFO</level>
        <file>/var/log/shop/shop.log</file>
        <maxFileSize>50MB</maxFileSize>
        <backupCount>10</backupCount>
        <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </logging>
    
    <security>
        <encryption>
            <algorithms>AES-256-GCM</algorithms>
            <key>shop_encryption_key_2025</key>
        </encryption>
        <authentication>
            <jwt>
                <secret>shop_jwt_secret_2025</secret>
                <expiration>86400</expiration>
            </jwt>
        </authentication>
    </security>
</config>