我有一个数组 - 像这样:
Array ( [0] => abc [1] => def [2] => ghi )
我有一个XML文件 - 就像这样:
<?xml version="1.0" encoding="utf-8" ?>
<ROOT>
<SECTION>
<PART1>abc</PART1>
<PART2>111</PART2>
<PART3>222</PART3>
</SECTION>
<SECTION>
<PART1>def</PART1>
<PART2>333</PART2>
<PART3>444</PART3>
</SECTION>
<SECTION>
<PART1>ghi</PART1>
<PART2>555</PART2>
<PART3>666</PART3>
</SECTION>
</ROOT>
我需要的是在XML文件PART1中查找数组的所有值,并在新数组中输出PART2,然后看起来像这样:
Array ( [0] => 111 [1] => 333 [2] => 555 )
答案 0 :(得分:0)
使用SimpleXMLElement
类:
$arr = ['abc', 'def', 'ghi'];
$sxe = simplexml_load_file($your_xmlfile);
$part2 = [];
foreach ($sxe->SECTION as $s) {
if (in_array($s->PART1, $arr)) $part2[] = (string) $s->PART2;
}
print_r($part2);
输出:
Array ( [0] => 111 [1] => 333 [2] => 555 )
答案 1 :(得分:0)
您可以使用数组中的值来创建Xpath表达式,以获取所需的值:
import os
import csv
from collections import Counter, OrderedDict
def count_attributes(file_name):
with open(file_name, encoding='utf-8', newline='') as csv_file:
reader = csv.DictReader(csv_file)
counters = OrderedDict((attr, Counter()) for attr in reader.fieldnames)
for row in reader:
for attr, value in row.items():
counters[attr][value] += 1
return counters
if __name__ == '__main__':
# data_file = os.path.join("..", "data", "thecsvfile.csv")
data_file = "thecsvfile.csv" # Slight simplification for testing.
for attr, counts in count_attributes(data_file).items():
print('{}: {}'.format(attr.replace('_', ' '), dict(counts)))