XML filter

In this example below you will see how to do a XML filter with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by trien, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright trien ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>XML filter</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <html lang="en">
<head>
    <meta charset="UTF-8">
    <title>XML filter</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="https://codepen.io/trien/pen/ZrombV.css">
</head>
<body>
<div class="container">
    <h1 class="display-3 text-center"><img src="images/xmlFilter_logo.png" alt=""></h1>
    <h2 class="mb-3">1. Extract</h2>
    <div class="row">
        <div class="col-md-12">
            <input id="file" type="file" aria-describedby="passwordHelpInline">
            <small id="helpInline" class="text-muted">
              Administration >  Site Development >  Import & Export
            </small>
        </div>
    </div>

    <h2 class="my-3">2. Configure</h2>
    <div class="row" id="configure">
        <div class="col-md-12">
            <div class="alert alert-info" role="alert">
                Separate ids with ","
            </div>
        </div>
    </div>

    <h2 class="my-3">3. Process</h2>
    <div class="row">
        <div class="col-md-12">
            <a id="filter" class="btn btn-primary btn-lg disabled" href="javascript:void(0);">Filter xml</a>
            <a id="dl" class="btn btn-success btn-lg disabled" download="export.xml">Download</a>
        </div>
    </div>
    
    <h2 class="mt-3">4. Log</h2>
    <div id="log">
        <div class="row" id="logs"></div>
    </div>
</div>
    
    <script src="https://codepen.io/trien/pen/ZrombV.js"></script>
</body>
</html>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/trien/xml-filter-ZrombV */
label {
  display: block;
  text-align: center;
}

textarea {
  width: 100%;
  height: 100px;
}

ul {
  padding-left: 0;
  height: 20vh;
  overflow: auto;
}


/*Downloaded from https://www.codeseek.co/trien/xml-filter-ZrombV */
let query = new URLSearchParams(window.location.search),
    filePath,
    tags = [
      {
        name: 'type-extension',
        filterId: 'type-id',
        default: 'SitePreferences',
        selection: null,
        logElement: null
      },
      {
        name: 'attribute-definition',
        filterId: 'attribute-id',
        selection: null,
        logElement: null,
        default: ''
      },
      {
        name: 'attribute-group',
        filterId: 'group-id',
        selection: null,
        logElement: null,
        default: ''
      }
    ];
console.log(query);
tags.forEach(tag => {
  let confWrap = document.createElement('div'),
      textarea = document.createElement('textarea'),
      cleanText = t => t.target.value = t.target.value.trim();
  confWrap.classList.add('col-md-4');
  confWrap.innerHTML = `<label for="${tag.name}">${tag.name}</label>`;
  textarea.classList.add('px-2');
  textarea.setAttribute('placeholder', `${tag.name} ids`);
  textarea.value = tag.default;
  textarea.addEventListener('keyup', e => cleanText(e));
  textarea.addEventListener('change', e => cleanText(e));
  confWrap.appendChild(textarea);
  configure.appendChild(confWrap);  
  tag.selection = textarea;

  let logWrap = document.createElement('div'),
      log = document.createElement('ul');
  logWrap.classList.add('col-md-4');
  logWrap.innerHTML = `<strong>Removed ${tag.name}s</strong>`;
  logWrap.appendChild(log);
  logs.appendChild(logWrap);
  tag.logElement = log;
});
file.addEventListener('change', e => {
    filePath = e.target.files[0];
    filter.classList.remove('disabled');
    dl.classList.add('disabled');
});
filter.addEventListener('click', () => {
  tags.forEach(tag => tag.logElement.innerHTML = '');
  if (filePath) {
    fetch(URL.createObjectURL(filePath))
      .then(response => response.text())
      .then(str => (new window.DOMParser()).parseFromString(str, "text/xml"))
      .then(xml => {
      tags.forEach(tag => {
        let nodes = xml.documentElement.getElementsByTagName(tag.name);
        for (let i = 0; i <= nodes.length - 1; i++) {
          let node = nodes[i],
              id = node.getAttribute(tag.filterId);
          if (!tag.selection.value.split(',').includes(id)) {
            node.parentNode.removeChild(node);
            i--; //decrease index pointer
            tag.logElement.innerHTML+= `<li>${id}</li>`;
          } else { console.log(`keeped ${tag.name} ${id}`); }
        }
      });
      dl.classList.remove('disabled');
      let xmlString = new XMLSerializer()
        .serializeToString(xml)
        .replace(/^\s*$[\n\r]{1,}/gm, '');
      dl.setAttribute('href', 'data:text/xml;charset=utf-8,' + encodeURIComponent(xmlString));
      //dl.setAttribute('href', URL.createObjectURL(xmlString));
    });
  }
});

Comments