Замена угловых скобок внутри элементов XML

Рейтинг: 0Ответов: 1Опубликовано: 07.06.2023

Как отловить и заменить угловые скобки внутри элементов XML-файла? Парсить по закрывающим тегам? Структура XML и названия полей заранее не известны, как и попадающиеся скобки, для примера:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE recipe>
<recipe name="хлеб" preptime="5min" cooktime="180min">
   <title>
      Простой хлеб
   </title>
   <composition>
      <mainIngredient amount="3" unit="стакан">Мука <<Кубиночка>></mainIngredient>
      <ingredient amount="0.25" unit="грамм">Дрожжи <Минутка></ingredient>
      <ingredient amount="1.5" unit="стакан">Тёплая(>35 С) вода</ingredient>
   </composition>
</recipe>

Ответы

▲ 2Принят

Как отловить и заменить угловые скобки внутри элементов XML-файла?

Можно обработать текст регулярным выражением...

let data = `<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE recipe>
<recipe name="хлеб" preptime="5min" cooktime="180min">
   <title>
      Простой хлеб
   </title>
   <composition>
      <mainIngredient amount="3" unit="стакан">Мука <<Кубиночка>></mainIngredient>
      <ingredient amount="0.25" unit="грамм">Дрожжи <Минутка></ingredient>
      <ingredient amount="1.5" unit="стакан">Тёплая(>35 С) вода</ingredient>
   </composition>
</recipe>`
const re = /(<([a-z]+)[^>]*>)(.*)(<\/\2>)/gi
data = data.replace(re, (_, a, b, c, d) => {
  c = c.replace(/[<>]/g, '-')
  return a + c + d
})
console.log(data)

Или вот такой вариант...

let data = `<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE recipe>
<recipe name="хлеб" preptime="5min" cooktime="180min">
   <title>
      Простой хлеб
   </title>
   <composition>
      <mainIngredient amount="3" unit="стакан">Мука <<Кубиночка>></mainIngredient>
      <ingredient amount="0.25" unit="грамм">Дрожжи <Минутка></ingredient>
      <ingredient amount="1.5" unit="стакан">Тёплая(>35 С) вода</ingredient>
   </composition>
</recipe>`
const re = /(<([a-z]+)[^>]*>)(.*)(<\/\2>)/gi
data = data.replace(re, (_, a, b, c, d) => {
  return a + `![CDATA[${c}]]` + d
})
console.log(data)