www.gusucode.com > mcms手机网站系统 v3.1源码程序 > mcms_v3.1.0/upload/class/xml.class.php

    <?php
/**
 * XML 处理类
 * @author wangzhongbin
 */
class XmlHandle {
	private $xmlDoc;
	private $xpath;
	
	/**
	 *构造函数
	 * @param $doc XML 文档
	 * */
	public function __construct($doc) {
		if ($doc instanceof DOMDocument)
			$this->xmlDoc = $doc;
		else
			throw new Exception("@param 不是DOMDocument类型");
		$this->xpath = $this->getDOMXPath($this->xmlDoc);
	}
	
	/**
	 * 构造函数
	 * @param $xmlFilePath 文件路径 (物理路径)
	 * @return XmlHandle 对象
	 * */
	public static function createXmlHandle($xmlFilePath) {
		$doc = new DOMDocument();
		$doc->load($xmlFilePath);
		$xmlHandle = new XmlHandle($doc);
		return $xmlHandle;
	}
	
	/**
	 * 获取 DOMXPath 对象
	 * @param $document XML 文档
	 * @return DOMXPath 对象
	 * */
	private function getDOMXPath($document) {
		$domxpath = new DOMXPath ($document);
		return $domxpath;
	}
	
	/**
	 * 选择匹配 xpath 表达式的第一个 DomNode
	 * @param string $xpath 表达式
	 * @return DomNode 对象
	 * */
	public function selectSingleNode($xpath) {
		$nodeList = $this->xpath->query($xpath);
		if ($nodeList->length > 0) {
			$node = $nodeList->item(0);
		}
		else {
			throw new Exception("xpath 表达式的过程中发生错误");
		}
		return $node;
	}
	
	/**
	 * 获取指定节点列表
	 * @param string $xpath 表达式
	 * @param string $childNodeName 指定节点下子节点的名称
	 * @return DOMNodeList 对象
	 * */
	public function getNodeList($xpath, $childNodeName='') {
		if (!empty($childNodeName)) {
			$nodeList = $this->xpath->query($xpath.'/'.$childNodeName);
		}
		else {
			$nodeList = $this->xpath->query($xpath);
		}
		return $nodeList;
	}
	
	/**
	 * 获取指定节点
	 * @param string $xpath 表达式
	 * @param string $childNodeName 指定节点下子节点的名称
	 * @return DomNode 对象
	 * */
	public function getNode($xpath, $childNodeName='') {
		if (!empty($childNodeName)) {
			$node = $this->selectSingleNode($xpath.'/'.$childNodeName);
		}
		else {
			$node = $this->selectSingleNode($xpath);
		}
		return $node;
	}
	
	/**
	 * 获取指定节点的值
	 * @param string $xpath 表达式
	 * @param DomNode $node 对象
	 * @return string 节点的值
	 * */
	public function getValue($xpath) {
		return $this->getNode($xpath)->nodeValue;
	}
}
?>