开发者

How to read the randomly/dynamic xml tag name that i don't know?

I would like to perform a xml data exchange as开发者_Python百科 below:

The incoming xml data have some tags i don't know about the tag name.

Can i read those tag without knowing the tag name? Also how can i get the tag name as the data attribute?

For example: i want to read different patients record. Every patient have different disease. Such as 'Heart Disease', 'cancer'.

<heart disease>serious</heart disease>
<cancer>normal</cancer>

I don't know both tags before. but i want to read the tag name and present it. Finally, i can get data: heart disease: serious cancer normal:


Yes, you can, e.g. with Simple XML:

$xml = new SimpleXMLElement($fileName, NULL, true);

foreach ($xml->children() as $child)
{
    print child->getName();

    foreach ($child->attributes() as $attribute)
    {
        print $attribute.', ';
    }
}


Well, I feel that I should first warn you that white-space does not make for valid XML tags. You can add <white space>STUFF</white space>, but that will read as a <white> tag. With a more forgiving interpreter, you might find that it has a true space boolean attribute. Replace the \s with -.

With DOMDocument, to read child nodes without knowing anything about them, other than the fact that they are child nodes, you would use the appropriately named childNodes property:

$doc = new DOMDocument();
$rand = rand(1,100);
$doc->loadXML('<root><i'.$rand.'><cannot-know-i /></i'.$rand.'></root>');
foreach( $doc->documentElement->childNodes as $node )
    print $node->nodeName; // i$rand


I suggest you format the XML into another format. In a format you DO know. Something like this:

<?xml version="1.0" ?> 
    <Information>
        <Disease target="heart" />
        <Cancer type="normal" />
    </Information>
</xml>

Then you can use every parser that is available in your programming language (PHP in your case).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜