xml xpath и вложение в python - PullRequest
0 голосов
/ 18 марта 2020

Я пытаюсь распечатать описание в пределах .//statement/statement/description, которое будет следующим:

"Реализует процесс обеспечения того, чтобы организационные планы по проведению тестирования безопасности, обучения и мониторинга действий, связанных с информационные системы организации: «

» Проверяет планы тестирования, обучения и мониторинга на предмет соответствия стратегии управления рисками организации и общеорганизационными приоритетами действий по реагированию на риски. »

, но для по какой-то причине он также углубляется и печатает следующие два утверждения:

"Разработаны и поддерживаются; и"

"Продолжайте выполняться своевременно;"

Это порядок, в котором он печатается в

Реализует процесс обеспечения того, чтобы организационные планы по проведению тестирования безопасности, обучения и мониторинга действий, связанных с информационными системами организации:

Отзывы о тестировании, планы обучения и мониторинга в соответствии с организационной стратегией управления рисками и общеорганизационными приоритетами для действий по реагированию на риски.

Разрабатываются и поддерживаются; и

Продолжать выполняться своевременно;

что я должен изменить, чтобы печатать только

Реализация процесса для обеспечения того, чтобы организационная планы проведения мероприятий по тестированию, обучению и мониторингу безопасности, связанных с информационными системами организации:

Проверка планов тестирования, обучения и мониторинга на предмет соответствия стратегии управления рисками организации и общеорганизационными приоритетами действий по реагированию на риски.

Python код

import xml.etree.ElementTree as ET 
import csv


xmlFile='/Users/username/Desktop/xmlFile.xml'
tree = ET.parse(xmlFile) 
root = tree.getroot()

# open a file for writing
excelFile = open('/Users/username/Desktop/table2.csv', 'w')

# creates the csv writer object / varible to write to csv
csvwriter = csv.writer(excelFile)

# list that contains the header
list_head = []
count = 0

for element in root.findall('control'):
    list_nodes=[]
    if count == 0:

        number = element.find('number').tag
        list_head.append(number)

        description =element.find('.//statement/description').tag
        list_head.append(description)

        csvwriter.writerow(list_head)
        count = count + 1

    # Control number 
    number = 'Nist800-53-V4-' + element.find('number').text  
    list_nodes.append(number)


    # Control Description 
    if element.find('.//statement'):
        if element.find('.//statement/statement/') is not None:
            for descrip in element.findall('.//statement/statement/description'):
                descrip_value = descrip.text
                print(descrip_value)

    csvwriter.writerow(list_nodes)
excelFile.close()

XML файл

<?xml version="1.0" encoding="UTF-8"?>
<controls>
  <control>
    <family>PROGRAM MANAGEMENT</family>
    <number>PM-14</number>
    <title>TESTING, TRAINING, AND MONITORING</title>
    <statement>
      <description>The organization:</description>
      <statement>
        <number>PM-14a.</number>
        <description>
        Implements a process for ensuring that organizational plans for conducting security testing, training, and monitoring activities associated with organizational information systems:
        </description>
        <statement>
          <number>PM-14a.1.</number>
          <description>Are developed and maintained; and</description>
        </statement>
        <statement>
          <number>PM-14a.2.</number>
          <description>Continue to be executed in a timely manner;</description>
        </statement>
      </statement>
      <statement>
        <number>PM-14b.</number>
        <description>
        Reviews testing, training, and monitoring plans for consistency with the organizational risk management strategy and organization-wide priorities for risk response actions.
        </description>
      </statement>
    </statement>
    <supplemental-guidance>
      <description>
      This control ensures that organizations provide oversight for the security testing, training, and monitoring activities conducted organization-wide and that those activities are coordinated. With the importance of continuous monitoring programs, the implementation of information security across the three tiers of the risk management hierarchy, and the widespread use of common controls, organizations coordinate and consolidate the testing and monitoring activities that are routinely conducted as part of ongoing organizational assessments supporting a variety of security controls. Security training activities, while typically focused on individual information systems and specific roles, also necessitate coordination across all organizational elements. Testing, training, and monitoring plans and activities are informed by current threat and vulnerability assessments.
      </description>
      <related>AT-3</related>
      <related>CA-7</related>
      <related>CP-4</related>
      <related>IR-3</related>
      <related>SI-4</related>
    </supplemental-guidance>
    <references>
      <reference>
        <item xml:lang="en-US" href="https://csrc.nist.gov/publications/search?keywords-lg=800-16">NIST Special Publication 800-16</item>
      </reference>
      <reference>
        <item xml:lang="en-US" href="https://csrc.nist.gov/publications/search?keywords-lg=800-37">NIST Special Publication 800-37</item>
      </reference>
      <reference>
        <item xml:lang="en-US" href="https://csrc.nist.gov/publications/search?keywords-lg=800-53A">NIST Special Publication 800-53A</item>
      </reference>
      <reference>
        <item xml:lang="en-US" href="https://csrc.nist.gov/publications/search?keywords-lg=800-137">NIST Special Publication 800-137</item>
      </reference>
    </references>
  </control>
</controls>

1 Ответ

2 голосов
/ 18 марта 2020

Ваше выражение XPath

.//statement/description

извлекает все элементы <description>, которые являются прямым потомком элемента <statement>. Их много - как вы уже видели.
Измените выражение на

statement/statement/description

, и вы получите желаемый результат, потому что вы выберете только те элементы <description>, которые имеют двух <statement> предков. (не точно, но достаточно, чтобы понять суть).

...