从SimpleXmlElement读取命名空间属性(从XMLReader导入) [英] Read a namespaced attribute from a SimpleXmlElement (imported from XMLReader)
问题描述
我正在尝试读取一个较大的xml文件(大约40 MB),并使用此数据来更新我的应用程序的数据库。
I'm trying to read a large xml file (about 40 MB), and use this data for update the db of my application.
似乎我在使用XMLReader和simplexml_import_dom()的时间/内存方面,我找到了一个很好的折衷方法,但是我无法获得名称中带有冒号的属性值。例如< g:attr_name>
。
It seems i've found a good compromise in terms of elapsed time/memory using XMLReader and simplexml_import_dom() but i can't get the value of attributes with colon in their name... for example <g:attr_name>
.
如果我仅对每个产品节点使用$ reader-> read()函数,则可以将值作为$ reader- >值,但是如果我将节点expand()并使用$ doc-> importNode复制该属性,则将忽略该属性。
If i simply use $reader->read() function for each "product" node i can retrive the value as $reader->value, but if i expand() the node and copy it with $doc->importNode this attributes are ignored.
$reader = new XMLReader();
$reader->open(__XML_FILE__);
$doc = new DOMDocument;
while ($reader->read()) {
switch ($reader->nodeType) {
case (XMLREADER::ELEMENT):
if($reader->localName=="product"){
$node = simplexml_import_dom($doc->importNode($reader->expand(), true));
echo $node->attr_name."<br><br>";
$reader->next('product');
}
}
}
可能我错过了某件事...任何建议都将被采纳!
Probably i miss something... any advice would be really appriciated!
谢谢。
推荐答案
名称中带有冒号的属性 命名空间 。
Attributes with colons in their name have a namespace.
冒号前的部分是已注册到某些命名空间(通常在根节点中)的前缀。要访问 SimpleXmlElement
的命名空间属性,必须将命名空间传递给 attributes()
方法:
The part before the colon is a prefix that is registered to some namespace (usually in the root node). To access the namespaced attributes of a SimpleXmlElement
you have to pass the namespace to the attributes()
method:
$attributes = $element->attributes('some-namespace'); // or
$attributes = $element->attributes('g', TRUE); // and then
echo $attributes['name'];
这同样适用于节点的子元素。通过 childrens()
方法
The same applies to element children of a node. Access them via the childrens()
method
$children = $element->children('some-namespace'); // or
$children = $element->children('g', TRUE); // and then
echo $children->elementName;
在旁注中,如果要将数据导入数据库,也可以尝试执行所以直接:
On a sidenote, if you want to import this data to your database, you can also try to do so directly:
- http://dev.mysql.com/tech-resources/articles/xml-in-mysql5.1-6.0.html#xml-5.1-importing
这篇关于从SimpleXmlElement读取命名空间属性(从XMLReader导入)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!