qt读取xml文件读写源码
PHP5为开发人员提供了更多使用XML的能力。 诸如DOM,SimpleXML和XSL等新的和经过修改的扩展使使用XML的代码强度更低。 在PHP5中,DOM符合W3C标准。 最重要的是,这些扩展之间的互操作性非常重要,可提供附加功能,例如交换格式以扩展可用性,W3C的XPath等等。 在这里,您将看到输入和输出选项,并且将依赖Yahoo Web Services REST协议接口来提供更复杂的展示,以展示现在熟悉的DOM和SimpleXML扩展的功能,并以XSL扩展结束。
本系列以前
本系列的第一篇文章提供了有关XML的基本信息。 它着眼于快速入门的应用程序编程接口(API),并演示了SimpleXML如何与必要的文档对象模型(DOM)结合使用,是处理简单,可预测且相对基本的XML文档的理想选择。 第2部分研究了PHP5中可用于XML的解析API的广度,包括SimpleXML,DOM,XML的简单API(SAX)和XMLReader,并考虑了哪种解析技术最适合不同大小和复杂性的XML文档。
PHP5中的XML
可扩展标记语言(XML)被描述为标记语言和基于文本的数据存储格式,它提供了一种基于文本的方式来对信息应用和描述基于树的结构。 在这里,您将了解Web服务上下文中的XML,这可能是推动XML在企业界之外的最新增长的最重要因素之一。
在PHP5中,存在用于操纵XML的全新的和完全重写的扩展,所有扩展都基于相同的libxml2代码。 这个共同的基础提供了这些扩展之间的互操作性,从而扩展了每个扩展的功能。 基于树的解析器包括SimpleXML,DOM和XSLT处理器。 如果您熟悉其他语言的DOM,那么使用PHP中的类似功能进行编码将比以前更加轻松。 基于流的解析器包括XML的简单API(SAX)和XMLReader。 SAX的功能与PHP4相同。
使用DOM处理XML
您可以用来操作XML文件。 仅当XML文件相对较小时,使用DOM才有效。 使用此方法的优点是熟悉的W3C DOM的坚实标准,其方法以及编码带来的灵活性。 DOM的缺点是大型文档的编码困难和性能问题。
行动中的DOM
使用DOM,您可以构建,修改,查询,验证和转换XML文档。 可以使用所有DOM方法和属性,并且大多数DOM级别2方法都是通过适当支持的属性来实现的。 凭借DOM的巨大灵活性,使用DOM解析的文档可能会变得很复杂。 但是请记住,如果一次将一个大型XML文档全部加载到内存中,那么灵活性的代价是有代价的。
本文中的示例使用Yahoo的搜索API,PHP5和REpresentational State Transfer(REST)来说明在有趣的应用程序环境中DOM的用法。 雅虎之所以选择REST,是因为开发人员普遍认为REST可以以20%的成本提供SOAP优势的80%。 我之所以选择此应用程序来展示PHP / XML,是因为Web服务的普及可能是推动XML在企业界之外的最新增长的最重要因素之一。
通常,REST通过以服务条目URL开头,然后以查询字符串的形式附加搜索参数来形成请求。 然后, 清单1使用DOM扩展解析查询结果。
清单1.使用DOM的Yahoo Demo代码示例
<?php
//This query does a search for any Web pages relevant to "XML Query"
$query = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?".
"query=%5C%22XML%20Query%5C%22&appid=YahooDemo";
//Create the DOM Document object from the XML returned by the query
$xml = file_get_contents($query);
$dom = new DOMDocument;
$dom = DOMDocument::loadXML($xml);
function xml_to_result($dom) {
//This function takes the XML document and maps it to a
//PHP object so that you can manipulate it later.
//First, retrieve the root element for the document
$root = $dom->firstChild;
//Next, loop through each of its attributes
foreach($root->attributes as $attr) {
$res[$attr->name] = $attr->value;
}
//Now, loop through each of the children of the root element
//and treat each appropriately.
//Start with the first child node. (The counter, i, is for
//tracking results.
$node = $root->firstChild;
$i = 0;
//Now keep looping through as long as there is a node to work
//with. (At the bottom of the loop, the code moves to the next
//sibling, so when it runs out of siblings, the routine stops.
while($node) {
//For each node, check to see whether it's a Result element or
//one of the informational elements at the start of the document.
switch($node->nodeName) {
//Result elements need more analysis.
case 'Result':
//Add each child node of the Result to the result object,
//again starting with the first child.
$subnode = $node->firstChild;
while($subnode) {
//Some of these nodes just are just whitespace, which does
//not have children.
if ($subnode->hasChildNodes()){
//If it does have children, get a NodeList of them, and
//loop through it.
$subnodes = $subnode->childNodes;
foreach($subnodes as $n) {
//Again check for children, adding them directly or
//indirectly as appropriate.
if($n->hasChildNodes()) {
foreach($n->childNodes as $cn){
$res[$i][$subnode->nodeName][$n->nodeName]=
trim($cn->nodeValue);
}
} else {
$res[$i][$subnode->nodeName]=trim($n->nodeValue);
}
}
}
//Move on to the next subnode.
$subnode = $subnode->nextSibling;
}
$i++;
break;
//Other elements are just added to the result object.
default:
$res[$node->nodeName] = trim($node->nodeValue);
break;
}
//Move on to the next Result of informational element
$node = $node->nextSibling;
}
return $res;
}
//First, convert the XML to a DOM object you can manipulate.
$res = xml_to_result($dom);
//Use one of those "informational" elements to display the total
//number of results for the query.
echo "<p>The query returns ".$res["totalResultsAvailable"].
" total results The first 10 are as follows:</p>";
//Now loop through each of the actual results.
for($i=0; $i<$res['totalResultsReturned']; $i++) {
echo "<a href='".$res[$i]['ClickUrl']."'><b>".
$res[$i]['Title']."</b></a>: ";
echo $res[$i]['Summary'];
echo "<br /><br />";
}
?>
使用SimpleXML处理XML
SimpleXML扩展是处理XML文档的一种选择工具,前提是XML文档不会太复杂或太深,并且不包含任何混合内容。 顾名思义,SimpleXML比DOM更容易编码。 如果使用已知的文档结构,它将更加直观。 libXML2体系结构的互操作性极大地提高了DOM和SimpleXML的灵活性,允许导入将格式从DOM交换到SimpleXML并随意转换。
运行中的SimpleXML
使用SimpleXML操作的文档简单而又快速地编写代码。 以下代码使用SimpleXML扩展名解析查询结果。 如您所料,下面的SimpleXML代码(请参见清单2 )比上面清单1所示的DOM代码示例更紧凑。
清单2. Yahoo SimpleXML示例
<?php
//This query does a search for any Web pages relevant to "XML Query"
$query = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?".
"query=%5C%22XML%20Query%5C%22&appid=YahooDemo";
$xml = simplexml_load_file($query);
// Load up the root element attributes
foreach($xml->attributes() as $name=>$attr) {
$res[$name]=$attr;
}
//Use one of those "informational" elements to display the total
//number of results for the query.
echo "<p>The query returns ".$res["totalResultsAvailable"].
" total results The first 10 are as follows:</p>";
//Unlike with DOM, where we loaded the entire document into the
//result object, with SimpleXML, we get back an object in the
//first place, so we can just use the number of results returned
//to loop through the Result members.
for($i=0; $i<$res['totalResultsReturned']; $i++) {
//The object represents each piece of data as a member variable
//rather than an array element, so the syntax is a little bit
//different from the DOM version.
$thisResult = $xml->Result[$i];
echo "<a href='".$thisResult->ClickUrl."'><b>".
$thisResult->Title."</b></a>: ";
echo $thisResult->Summary;
echo "<br /><br />";
}
?>
清单3向清单2的SimpleXML示例中添加了一个缓存层。 缓存将任何特定查询的结果缓存两个小时。
清单3.具有缓存层的Yahoo SimpleXML示例
<?php
//This query does a search for any Web pages relevant to "XML Query"
$query = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?".
"query=%5C%22XML%20Query%5C%22&appid=YahooDemo";
//The cached material should only last for 2 hours, so you need the
//current time.
$currentTime = microtime(true);
//This is where I put my tempfile; you can store yours in a more
//convenient location.
$cache = 'c:\temp\yws_'.md5($query);
//First check for an existing version of the time, and then check
//to see whether or not it's expired.
if(file_exists($cache) &&
filemtime($cache) > (time()-7200)) {
//If there's a valid cache file, load its data.
$data = file_get_contents($cache);
} else {
//If there's no valid cache file, grab a live version of the
//data and save it to a temporary file. Once the file is complete,
//copy it to a permanent file. (This prevents concurrency issues.)
$data = file_get_contents($query);
$tempName = tempnam('c:\temp','YWS');
file_put_contents($tempName, $data);
rename($tempName, $cache);
}
//Wherever the data came from, load it into a SimpleXML object.
$xml = simplexml_load_string($data);
//From here, the rest of the file is the same.
// Load up the root element attributes
foreach($xml->attributes() as $name=>$attr) {
$res[$name]=$attr;
}
...
使用XSL操纵XML
可扩展样式表语言(XSL)是一种功能性XML语言,是为处理XML文档而创建的。 使用XSL,您可以根据样式表定义将XML文档转换为重新定义的XML文档,XHTML文档,HTML文档或文本文档,类似于通过实现规则来实现CSS的方式。 PHP5的W3C标准实现支持与DOM和XPath的互操作性。 可扩展样式表语言转换(XSLT)是基于libxml2的XML扩展,其样式表是XML文档。 XSLT将XML源树转换为XML或XML类型的结果树。 这些转换将样式表中指定的一系列规则应用于XML数据。 XSLT可以在输出文件中添加或删除元素或属性。 它允许开发人员对元素进行排序或重新排列,并决定要隐藏或显示哪些元素。 不同的样式表允许您的XML针对不同的媒体适当显示,例如屏幕显示与打印显示。 XSLT使用XPath导航原始XML文档。 XSLT转换模型通常包含一个源XML文件,一个包含一个或多个处理模板的XSLT文件以及一个XSLT处理器。 XSLT文档必须使用DOM加载。 PHP5仅支持libxslt处理器。
XSL的实际应用
XSL的一个有趣的应用是动态创建XML文件,以包含刚从数据库中选择的任何数据。 使用此技术,可以创建完整的Web应用程序,其中PHP脚本由数据库查询中的XML文件组成,然后使用XSL转换生成实际HTML文档。
此方法将表示层与业务层完全分开,因此您可以独立维护另一层。
清单4展示了XML输入文件,XSL样式表,XSLT处理器和多个可能的输出之间的关系。
清单4. XML转换
<?php
// Create new XSLTProcessor
$xslt = new XSLTProcessor();
//Both the source document and the stylesheet must be
//DOMDocuments, but the result can be a DOMDocument,
//a file, or even a String.
// Load the XSLT stylesheet
$xsl = new DOMDocument();
$xsl->load('recipe.xsl');
// Load the stylesheet into the processor
$xslt->importStylesheet($xsl);
// Load XML input file
$xml = new DOMDocument();
$xml->load('recipe.xml');
//Now choose an output method and transform to it:
// Transform to a string
$results = $xslt->transformToXML($xml);
echo "String version:";
echo htmlentities($results);
// Transform to DOM object
$results = $xslt->transformToDoc($xml);
echo "The root of the DOM Document is ";
echo $results->documentElement->nodeName;
// Transform to a file
$results = $xslt->transformToURI($xml, 'results.txt');
?>
摘要
本系列的较早部分集中于使用文档对象模型和SimpleXML来执行简单和复杂的解析任务。 第2部分还介绍了XMLReader的用法,它提供了一种更快,更轻松的方式来执行以前使用SAX可以执行的任务。
现在,在本文中,您了解了如何访问远程文件(例如基于REST的Web服务),以及如何使用XSLT轻松将XML数据输出到字符串,DOM Document对象或文件。
翻译自: https://www.ibm.com/developerworks/opensource/library/x-xmlphp3/index.html
qt读取xml文件读写源码