Как можно скопировать содержимое одного элемента (текстовую строку) и добавить к содержимому другого элемента? (XML) - PullRequest
0 голосов
/ 25 января 2019

Мне было поручено изменить тысячи файлов вопросов. В каждом файле один вопрос.

Мне нужно изменить файл, подобный этому ...

<xml>

<question>What is the fourth planet from the Sun?</question>

<answer choice="1">Mercury</answer>
<answer choice="2">Venus</answer>
<answer choice="3">Mars</answer>

<feedback choice="1">Incorrect.</feedback>
<feedback choice="2">Incorrect.</feedback>
<feedback choice="3">Correct.</feedback>

<extrafeedback>Mars is the fourth planet from the Sun and is the second smallest planet in the solar system. Named after the Roman god of war, Mars is also often described as the "Red Planet" due to its reddish appearance. </extrafeedback>

</xml>

... в это. «Extrafeedback» был добавлен перед закрывающими тегами «answer».

<xml>

<question>What is the fourth planet from the Sun?</question>

<answer choice="1">Mercury</answer>
<answer choice="2">Venus</answer>
<answer choice="3">Mars</answer>

<feedback choice="1">Incorrect. Mars is the fourth planet from the Sun and is the second smallest planet in the solar system. Named after the Roman god of war, Mars is also often described as the "Red Planet" due to its reddish appearance.</feedback>
<feedback choice="2">Incorrect. Mars is the fourth planet from the Sun and is the second smallest planet in the solar system. Named after the Roman god of war, Mars is also often described as the "Red Planet" due to its reddish appearance.</feedback>
<feedback choice="3">Correct. Mars is the fourth planet from the Sun and is the second smallest planet in the solar system. Named after the Roman god of war, Mars is also often described as the "Red Planet" due to its reddish appearance.</feedback>

<extrafeedback>Mars is the fourth planet from the Sun and is the second smallest planet in the solar system. Named after the Roman god of war, Mars is also often described as the "Red Planet" due to its reddish appearance.</extrafeedback>

</xml>

У меня есть Notepad ++ и Oxygen XML Editor, но я открыт для изучения чего-то нового.

Ответы [ 2 ]

0 голосов
/ 25 января 2019

Это можно сделать довольно просто, используя PowerShell. Если хотите, вы можете просто скопировать этот скрипт в буфер обмена, открыть консоль PowerShell, cd в каталог, содержащий копию ваших файлов XML, и вставить.

# // For each XML file...
gci *.xml | %{

    write-host -nonewline "Patching $($_.Name)... "

    # // Read its contents and cast as an XML object
    [xml]$xml = gc $_

    $extra = $xml.selectSingleNode("//extrafeedback/text()").data.trim()

    # // For each feedback element's text node not already containing $extra...
    $xml.selectNodes("//feedback/text()") | ?{ $_.data -NotMatch $extra } | %{
        $_.data += " $extra"
    }

    # // Save modified XML to original file
    $xml.save($_)
    write-host "done." -f green
}

Анализатор XML PowerShell удалит все потерянные пробелы в файлах XML. Возможно, скопируйте пару файлов XML в тестовый каталог и сначала выполните тестовый запуск. Изучите результаты перед передачей этого сценария в тысячи файлов XML.

0 голосов
/ 25 января 2019

Вы можете достичь этого довольно легко, применив XSLT к каждому из документов.С измененным преобразованием идентичности со специализированным шаблоном для feedback/text():

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  <xsl:output indent="yes"/>

  <xsl:template match="@*|node()">
      <xsl:copy>
          <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
  </xsl:template>

  <xsl:template match="feedback/text()">
    <xsl:value-of select="., /xml/extrafeedback" separator=" "/>
  </xsl:template>

</xsl:stylesheet>

С помощью oXygen вы можете настроить сценарий преобразования XSLT в применить пакетные преобразования к набору файлов.

...