我正在阅读一个看起来像这样但有更多产品的xml文件:
DECLARE
m_distcnt NUMBER := 3; -- num_distinct
m_density NUMBER := 1/1000; -- density
m_nullcnt NUMBER := 0; -- num_nulls
m_avgclen NUMBER := 10; -- avg_col_len
srec dbms_stats.statrec;
c_array dbms_stats.chararray;
BEGIN
srec.epc := 3;
c_array := dbms_stats.chararray('HELLO', 'WORLD', 'FIRST');
srec.bkvals := dbms_stats.numarray(20, 180, 800);
dbms_stats.prepare_column_values(srec, c_array);
dbms_stats.set_column_stats(USER, 'FBHIST_DEMO', 'TESTCOL',
distcnt => m_distcnt,
density => m_density,
nullcnt => m_nullcnt,
srec => srec,
avgclen => m_avgclen);
END;
/
我想阅读它,然后只使用“产品标签”中某处包含“免费”字样且没有“产品”标签和xml标题的产品进行保存。
我知道如何阅读并保存文件,但除了包含“免费”的产品外,我无法找到删除所有内容的最佳方法。
我试过了正则表达式,但它似乎不是最好的解决方案(主要是因为匹配不能正常工作):
<?xml version="1.0" encoding="iso-8859-1"?>
<products>
<product>
<company>company.com</company>
<category>Category A</category>
<brand>Alle!rgica</brand>
<product_name>Name A</product_name>
<productid>6230</productid>
<description>A nice description</description>
<price>125.50</price>
</product>
<product>
<company>Team.com</company>
<category>Category B // something</category>
<brand>New Nordic > Healthcare</brand>
<product_name>Name B</product_name>
<productid>9489</productid>
<description>Active Legs? Buy it now for free</description>
<price>188.00</price>
</product>
</products>
因此,在上述情况下,文件应仅包含:
preg_match_all('/<product>(.*?)(free|free-stuff)(.*?)<\/product>/is', $data, $result);
答案 0 :(得分:1)
使用xpath()
:
$xml = simplexml_load_string($x); // assume XML in $x
$result = $xml->xpath("//product[not(contains(., 'free'))]");
$result
包含一个<product>
- 节点数组SimpleXML
- 不包含&#34; free&#34;的元素。
输出:
foreach ($result as $r)
echo $r->asXML();
看到它正常工作:https://eval.in/338884
答案 1 :(得分:0)
使用此代码:
$xml = simplexml_load_file($filename);
foreach($xml->product as $product) {
foreach($product->children() as $child)
// lookup the pattern in all nodes inside product
if ($found = (false !== strpos((string)$child, 'free')))
// Found - we can don't continue searching
break;
// save product found
if ($found) $products[] = $product;
}
print_r( $products);