Как получить прямые дочерние элементы указанного тега в XML с помощью JQuery
Пожалуйста, проверьте код ниже. Мне нужно проверить только те дети, которые определены внутри родительского тега.
Если в этом родителе появляется какой-либо неожиданный ребенок, я должен сообщить об этом как об ошибке.
Это мой 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>
родитель имеет только дочерние теги, которые разрешены. В противном случае мне нужно добавить это как ошибку.
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"><'+xmlchild+'></span> is not allowed inside the <span class="highlight"><'+x+'></span> element</td><td class="'+classname+'">'+error_type+'</td></tr>');
}
});
}
};rd.readAsText(this.files[i]);
Но children()
код не работает. Что я делаю неправильно?
2 ответа
Способ выбора родительского узла нуждается в коррекции: используйте 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>
Что вы можете сделать, так это перебрать свои дочерние элементы родительского элемента по вашему выбору. Ваш родительский элемент в этом случае "местами".
Вы можете использовать функцию 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"><'+elements+'></span> is not allowed inside the <span class="highlight"><'+x+'></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>