我正在编写一个php应用程序来操作XML文件。 我尝试了Perl XML serializer / unserializer进行转换 XML-> php obj-> json用于操作 然后将json转换回xml以打印出来。
以下是原始XML的示例
<module name="AssignId" active="true" description="user description">
<dict name="params">
<entry key="Adds">
...
</entry>
</dict>
</module>
转换为JSON的看起来像这样:
{"name":"AssignId","active":"true","description":"add draggable class to figure","dict":{"name":"params","entry":[{"key":"Adds" ...
}}
,最终结果XML如下所示:
<name>AssignId</name>
<active>true</active>
<description>add draggable class to figure</description>
<dict>
<name>params</name>
<entry>
<XML_Serializer_Tag>
<key>Adds</key>
...
</XML_Serializer_Tag>
</entry>
</dict>
</name>
这是我的2个班级
class JSON_toXML {
var $jsonObj,
$phpObj,
$serializer;
public function __construct($options, $file_path) {
$this->serializer = new XML_Serializer($options);
$serializedDoc = $this->serializer->serialize(json_decode($file_path));
if ($serializedDoc === true) {
$this->jsonObj = $this->serializer->getSerializedData();
} else {
$this->jsonObj = NULL;
}
}
public function print_obj() {
echo "<pre>";
echo($this->jsonObj);
echo "</pre>";
}
}
class XML_toJSON {
var $phpObj,
$jsonObj,
$unserializer;
public function __construct($options, $file_path) {
$this->unserializer = &new XML_Unserializer($options);
$unserializedDoc = $this->unserializer->unserialize($file_path, true);
$this->phpObj = $this->unserializer->getUnserializedData();
$this->jsonObj = json_encode($this->phpObj);
}
public function print_phpObj() {
echo "<pre>";
print_r($this->phpObj);
echo "</pre>";
}
public function get_phpObj() {
return $this->phpObj;
}
public function print_jsonObj() {
echo $this->jsonObj;
}
public function get_jsonObj() {
return $this->jsonObj;
}
}
我想知道如何保持最终结果XML与原始格式相同? 也许有更好的方法来做到这一点? 谢谢!!!
答案 0 :(得分:2)
您需要能够区分属性和元素,但您的格式不会传达该信息。您需要从更改格式开始,可能是以下内容:
{
"element": "module",
"attribs": {
"name": "AssignId",
"active": "true",
"description": "add draggable class to figure"
},
"children": [
{
"element": "dict",
"attribs": {
"name": "params"
},
"children:" [
...
]
}
]
}