tags:

views:

419

answers:

2

I have the following XML from a .NET web service:

<?xml version="1.0" encoding="utf-8"?>
<DataSet>
  <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xs:element name="NewDataSet" msdata:IsDataSet="true">
      <xs:complexType>
        <xs:choice maxOccurs="unbounded">
          <xs:element name="Table1">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="GROUP_ID" type="xs:int" minOccurs="0" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:complexType>
    </xs:element>
  </xs:schema>
  <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
    <NewDataSet xmlns="">
      <Table1 diffgr:id="Table11" msdata:rowOrder="0" diffgr:hasChanges="inserted">
        <GROUP_ID>NUM</GROUP_ID>
      </Table1>
    </NewDataSet>
  </diffgr:diffgram>
</DataSet>

I need to access just the GROUP_ID node value, but want to know the easiest way to do this. So far I have been using DomDocument and DomXPath to query for that node, but I'm hoping there is a better way that I am missing:

$xml = new DomDocument();
$xml->load('file.xml');
$xp = new DomXPath($xml);
$result = $xp->query('//GROUP_ID');
$id = null;
foreach($result as $node){
  $id = $node->nodeValue;
  break;
}

Thanks!

A: 

The need to loop in some fashion is unfortunately necessary. If you were using simplexml you could write your code as simply as:

$xml = simplexml_load_file('file.xml');
$result = $sxe->xpath('//GROUP_ID');
while(list(,$node) = each($result)) {
    $id = (string) $node;
    break; // optional
}
hobodave
I was hoping to avoid the loop, but it looks (as you say), necessary. Not the "prettiest" code, but it works for what I need.
Rob
A: 

I also have the similar problem

Please tell me if you get the solution Its really imp.

Thanks Dhvani

dhvani
looks like Rob got a solution a while ago.
Matt Ellen
Yes, I essentially used the selected answer. Like I said, it won't win any awards for pretty code but it gets the job done.
Rob