Как получить прямые дочерние элементы указанного тега в XML с помощью JQuery - PullRequest
0 голосов
/ 08 октября 2018

Пожалуйста, проверьте код ниже.Мне нужно проверить только те дети, которые определены внутри родительского тега.

Если в этом родителе появляется какой-либо неожиданный ребенок, я должен сообщить об этом как об ошибке.

Это мой XML-файл:

<places>
  <Tirunelveli>XXXX</Tirunelveli>//allowed child of places
  <Tiruchendur></Tiruchendur>//allowed child of places
  <Alwar></Alwar>//allowed child of places
  <sweet></sweet>//not allowed child of places and i have to report this tag as error
</places>

Мне нужно проверить, что <places> parent имеет только разрешенные дочерние теги.В противном случае мне нужно добавить его как ошибку.

var rd = new FileReader();
rd.onload = function(e){  
var xmlDoc = $.parseXML(this.result);                   
var $xml = $(xmlDoc);
//check allowed child of front tag
check_allowed_direct_child("places", "Tirunelveli,Tiruchendur,Alwar", "RULE_002", "Fail");                  

//Function to check the x tag have only the alowed child y
function check_allowed_direct_child(x,y,rule,error_type)
{
    var child_array = y.split(',');
    var child_count=child_array.length;
    var ischild=""
    var xmlchild="";
    $xml.children(x).each(function()
    {
        ischild="no";
        xmlchild=this.value;
        for(i=0;i<count;i++)
        {
        if(child_array[i]==xmlchild)
        {
            ischild="yes";
        }
        }
        if(ischild=="no")
        {
            //count the total error and warnings
            check_total_error_warning(error_type);
            $("#validation_report").append('<tr class="err"><td><a href="Asset\Rules\Rule.html\#'+rule+'">'+rule+'</td><td><span class="highlight">&#x0003C;'+xmlchild+'&#x0003E;</span> is not allowed inside the <span class="highlight">&#x0003C;'+x+'&#x0003E;</span> element</td><td class="'+classname+'">'+error_type+'</td></tr>');
            }

            });
            }

};rd.readAsText(this.files[i]);

Но код children() не работает.Что я делаю не так?

Ответы [ 2 ]

0 голосов
/ 08 октября 2018

Что вы можете сделать, так это перебирать свои дочерние элементы по вашему выбору.Ваш родительский элемент в этом случае - "place" .

. Вы можете использовать функцию javascript .tagName, чтобы получить тип элемента дочернего элемента.Затем вы можете построить условие для проверки допустимого / запрещенного ребенка (ren).

Пример:

var rd = new FileReader();
var xmlDoc = $.parseXML(this.result);                   
var $xml = $(xmlDoc);
var classname='errorClass';

function check_allowed_direct_child(x="places",
				    y="Tirunelveli,Tiruchendur,Alwar",
                                    rule="RULE_002",
                                    error_type="Fail") {
    var notAllowedChild='sweet';
    var child_array=y.split(",");
    for(i=0; child_array.length > i; i++) {
        if(child_array[i] != notAllowedChild) {
	    alert(child_array[i]+' is an allowed child');
	}
    }
    $(''+x).children().each(function () {
        var elements=this.tagName.toLowerCase();
	if(elements == notAllowedChild) {
	    alert(elements+' is not an allowed child');
            $("#validation_report").append('<tr class="err"><td><a href="#">'+rule+'</td><td><span class="highlight">&#x0003C;'+elements+'&#x0003E;</span> is not allowed inside the <span class="highlight">&#x0003C;'+x+'&#x0003E;</span> element</td><td class="'+classname+'">'+error_type+'</td></tr>');
	}
    });
}
table, th, td {
   border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<places>
  <Tirunelveli>XXXX</Tirunelveli>
  <Tiruchendur></Tiruchendur>
  <Alwar></Alwar>
  <sweet></sweet>
</places>
<table id="validation_report"></table>
<br />
<button onclick="check_allowed_direct_child();">Test</button>
0 голосов
/ 08 октября 2018

Способ, которым вы выбираете родительский узел, нуждается в исправлении: используйте find, чтобы найти его, затем используйте children для этого результата (без аргумента), чтобы получить все дочерние элементы.

Если родительский узелкорень XML, тогда find не найдет его, но с addBack вы также можете включить корневой узел в совпадение.

Я бы также использовал camelCase для имен ваших функций и использовал jQueryфункции для построения динамического HTML.

Вот как это может выглядеть:

var $xml = $("<aa><bb></bb><cc></cc><dd></dd><ee></ee></aa>");
var className = "someClass"
 
//check allowed child of front tag
checkChildAllowed($xml, "aa", ["bb","cc","dd"], "RULE_002", "Fail");                   

//Function to check the x tag have only the allowed child y
function checkChildAllowed($xml, parent, allowedChildren, rule, errorType) {
    // Make sure to first locate the parent correctly:
    var $parent = $xml.find(parent).addBack(parent); 
    // Uppercase tag names as jQuery uses that HTML convention
    allowedChildren = allowedChildren.map(childName => childName.toUpperCase()); 
    $parent.children().each(function () {
        if (allowedChildren.includes(this.nodeName)) return; // tag is OK
        // Include this if that function is defined:
        //check_total_error_warning(error_type); 
        $("#validation_report").append( // Use jQuery functions
            $("<tr>").addClass("err").append(
                $("<td>").append(
                    $("<a>").attr("href", "Asset\Rules\Rule.html\#"+rule).text(rule)
                ),
                $("<td>").append(
                    $("<span>").addClass("highlight")
                               .text("<"+this.nodeName.toLowerCase()+">"),
                    " is not allowed inside the ",
                    $("<span>").addClass("highlight").text("<"+parent+">"),
                    " element"
                ),
                $("<td>").addClass(className).text(errorType)
            )
        );
    });
}
table { border-collapse: collapse }
td { border: 1px solid; padding: 5px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="validation_report"></table>
...