XMLDocument2 - com escopo, global
A API XMLDocument2 é um wrapper de objeto JavaScript para analisar e extrair dados XML de uma cadeia de caracteres XML.
Use esta classe JavaScript para criar um objeto a partir de uma cadeia de caracteres XML, geralmente um valor de retorno de uma invocação de serviço da Web ou a carga XML da Fila do ECC. O uso do objeto XMLDocument2 em uma regra de negócio JavaScript permite consultar valores diretamente dos elementos e atributos XML.
Uma cadeia de caracteres XML tem uma estrutura de árvore e as partes da estrutura são chamadas de nós. Um objeto XMLDocument2 lida com dois tipos de nó, elemento e elemento de documento. Um nó de elemento é um nó com um nome e possivelmente atributos e nós secundários. Um nó de elemento de documento é o nó raiz da árvore XML. É o único nó sem um nó primário.
XMLDocument2 com escopo - XMLDocument2()
Cria um objeto XMLDocument2.
| Nome | Tipo | Descrição |
|---|---|---|
| Nenhum |
XMLDocument2 com escopo - XMLDocument2( GlideScriptableInputStream inputStream)
Cria um objeto XMLDocument2 a partir de um fluxo de anexos.
| Nome | Tipo | Descrição |
|---|---|---|
| fluxo de entrada | GlideScriptableInputStream | O fluxo de entrada que o objeto XMLDocument2 encapsula. |
XMLDocument2 com escopo - createElement(String name)
Cria e adiciona um nó de elemento ao nó atual. O nome do elemento é a cadeia de caracteres passada como um parâmetro. O novo elemento não tem nós secundários de texto.
| Nome | Tipo | Descrição |
|---|---|---|
| nome | Cadeia de caracteres | O nome do novo elemento. |
| Tipo | Descrição |
|---|---|
| XMLNode | Nó XML atual. |
var xmlString = "<test>" +
" <one>" +
" <two att=\"xxx\">abcd1234</two>" +
" <three boo=\"yah\" att=\"yyy\">1234abcd</three>" +
" <two>another</two>" +
" </one>" +
" <number>1234</number>" +
"</test>";
var xmlDoc = new XMLDocument2();
xmlDoc.parseXML(xmlString);
xmlDoc.createElement("new2");
gs.info(xmlDoc);
?xml version="1.0" encoding="UTF-8"?>
<test>
<one>
<two att="xxx">abcd1234</two>
<three att="yyy" boo="yah">1234abcd</three>
<two>another</two>
</one>
<number>1234</number>
<new2></new2>
</test>XMLDocument2 com escopo - createElementWithTextValue(Nome da cadeia de caracteres, Valor da cadeia de caracteres)
Cria e adiciona um nó de elemento com um nó secundário de texto ao nó atual.
| Nome | Tipo | Descrição |
|---|---|---|
| nome | Cadeia de caracteres | Nome do elemento a ser adicionado. |
| valor | Cadeia de caracteres | Valor de texto do elemento. |
| Tipo | Descrição |
|---|---|
| XMLNode | Nó XML atual. |
var xmlString = "<test>" +
" <one>" +
" <two att=\"xxx\">abcd1234</two>" +
" <three boo=\"yah\" att=\"yyy\">1234abcd</three>" +
" <two>another</two>" +
" </one>" +
" <number>1234</number>" +
"</test>";
var xmlDoc = new XMLDocument2();
xmlDoc.parseXML(xmlString);
xmlDoc.createElementWithTextValue("new", "test");
gs.info(xmlDoc);
<?xml version="1.0" encoding="UTF-8"?>
<test>
<one>
<two att="xxx">abcd1234</two>
<three att="yyy" boo="yah">1234abcd</three>
<two>another</two>
</one>
<number>1234</number>
<new>test</new>
</test>XMLDocument2 com escopo - getDocumentElement()
Obtém o nó do elemento de documento do objeto XMLdocument2. O nó do elemento do documento é o nó raiz.
| Nome | Tipo | Descrição |
|---|---|---|
| Nenhum |
| Tipo | Descrição |
|---|---|
| XMLNode | O elemento do documento. |
var xmlString = "<test>" +
" <one>" +
" <two att=\"xxx\">abcd1234</two>" +
" <three boo=\"yah\" att=\"yyy\">1234abcd</three>" +
" <two>another</two>" +
" </one>" +
" <number>1234</number>" +
"</test>";
var xmlDoc = new XMLDocument2();
xmlDoc.parseXML(xmlString);
//returns the root node of the document tree.
var rootNode = xmlDoc.getDocumentElement();
gs.info(rootNode.getTextContent());
abcd1234 1234abcd another 1234XMLDocument2 com escopo - getFirstNode(String xPath)
Obtém o primeiro nó no xPath especificado.
<store>
<resources company="ABC Inc">
<resources type="servers" />
</resources>
<resources company="XYZ Inc">
<resource type="bookstore">
<book>
<title>Windows</title>
<price>10</price>
</book>
<book year="2009">
<title>Harry Potter</title>
<price>50</price>
</book>
<book year="1999">
<title>Learning XML</title>
<price>120</price>
</book>
<book year="2019">
<title>Learning Java</title>
<price>99</price>
</book>
</resource>
</resources>
</store> "/store/resources/resource[@type='bookstore']/book[@year='1999']",
"/store/resources/resource[@type='bookstore']/book[@year]",
"/store/resources/resource[@type='bookstore']/book[price > 100]" "/store/resources/resource[@type='bookstore']/book[2]",
"/store/resources/resource[@type='bookstore']/book[last()]",
"/store/resources/resource[@type='bookstore']/book[position()>2]" Para contornar isso, use xPath sem predicados, como "/store/resources/resource[@type='bookstore']/book") e filtre os nós no script usando os métodos getFirstNode() e getNextNode().
| Nome | Tipo | Descrição |
|---|---|---|
| xPath | Cadeia de caracteres | O xPath do qual o nó será obtido. |
| Tipo | Descrição |
|---|---|
| XMLNode | O primeiro nó. |
var xmlString = "<test>" +
" <one>" +
" <two att=\"xxx\">abcd1234</two>" +
" <three boo=\"yah\" att=\"yyy\">1234abcd</three>" +
" <two>another</two>" +
" </one>" +
" <number>1234</number>" +
"</test>";
var xmlDoc = new XMLDocument2();
xmlDoc.parseXML(xmlString);
var foo = xmlDoc.getFirstNode('/test/one/two');
gs.info(foo.getTextContent());
abcd1234XMLDocument2 com escopo - getNextNode(Object current)
Obtém o nó após o nó especificado.
| Nome | Tipo | Descrição |
|---|---|---|
| atual | Objeto | O nó atual. |
| Tipo | Descrição |
|---|---|
| XMLNode | O próximo nó. |
var xmlString = "<test>" +
" <one>" +
" <two att=\"xxx\">abcd1234</two>" +
" <three boo=\"yah\" att=\"yyy\">1234abcd</three>" +
" <two>another</two>" +
" </one>" +
" <number>1234</number>" +
"</test>";
var xmlDoc = new XMLDocument2();
xmlDoc.parseXML(xmlString);
var foo = xmlDoc. getFirstNode('/test/one/two');
var foo2 = xmlDoc.getNextNode(foo);
gs.info(foo.getTextContent());
gs.info(foo2.getTextContent());
abcd1234
anotherXMLDocument2 com escopo - getNode(String xPath)
Obtém o nó especificado no xPath.
| Nome | Tipo | Descrição |
|---|---|---|
| xPath | Cadeia de caracteres | xPath do nó a ser obtido. |
| Tipo | Descrição |
|---|---|
| XMLNode | Nó XML atual. |
/*
* Checks if given node indeed of given tag.
* Params:
* tag - String, name of tag to check
* node - XMLNode, node in which to check for the tag
* Returns:
* true, if tag is present
* false, otherwise
*/
function isNodeOfTag (node, tag) {
try {
if (tag == node.getNodeName()) {
gs.info("Given node belongs to tag " + tag);
return true;
}
} catch (error) {
gs.error("Given node might not belong to tag " + tag + ". Error while checking: " + error);
return false;
}
}
var xmlString = "<test>" +
" <one>" +
" <two att=\"xxx\">abcd1234</two>" +
" <three boo=\"yah\" att=\"yyy\">1234abcd</three>" +
" <two>another</two>" +
" </one>" +
" <number>1234</number>" +
"</test>";
var xmlDoc = new XMLDocument2();
xmlDoc.parseXML(xmlString);
var node = xmlDoc.getNode("/test/one/two"); // tag 'two' is present in this XML.
isNodeOfTag(node, "two");
var node = xmlDoc.getNode("/test/one/four"); // tag 'four' is not present in this XML.
isNodeOfTag(node, "four");
Given node belongs to tag two
Given node might not belong to tag four. Error while checking: java.lang.NullPointerExceptionXMLDocument2 com escopo - getNodeText(String xPath)
Obtém todos os nós secundários de texto do nó referenciado no XPath especificado.
| Nome | Tipo | Descrição |
|---|---|---|
| xPath | Cadeia de caracteres | XPath do texto a ser obtido. |
| Tipo | Descrição |
|---|---|
| Cadeia de caracteres | Textos secundários no XPath. |
var xmlString = "<test>" +
" <one>" +
" <two att=\"xxx\">abcd1234</two>" +
" <three boo=\"yah\" att=\"yyy\">1234abcd</three>" +
" <two>another</two>" +
" </one>" +
" <number>1234</number>" +
"</test>";
var xmlDoc = new XMLDocument2();
xmlDoc.parseXML(xmlString);
gs.info(xmlDoc.getNodeText("//two"));
Saída:
abcd1234
XMLDocument2 com escopo - parseXML(String xmlDoc)
Analisa a cadeia de caracteres XML e a carrega no objeto XMLDocument2.
| Nome | Tipo | Descrição |
|---|---|---|
| xmlDoc | Cadeia de caracteres | O documento a ser analisado. |
| Tipo | Descrição |
|---|---|
| Booliano | Sinalizador que indica se o conteúdo foi analisado. |
Este exemplo analisa o xmlString e o carrega no objeto xmlDocument2.
var xmlString = "<test>" +
" <one>" +
" <two att=\"xxx\">abcd1234</two>" +
" <three boo=\"yah\" att=\"yyy\">1234abcd</three>" +
" <two>another</two>" +
" </one>" +
" <number>1234</number>" +
"</test>";
var xmlDoc = new XMLDocument2();
xmlDoc.parseXML(xmlString);
var rootNode = xmlDoc.getDocumentElement();
XMLDocument2 com escopo - setCurrentElement(elemento XMLNode)
Torna o nó passado como um parâmetro o nó atual.
| Nome | Tipo | Descrição |
|---|---|---|
| elemento | XMLNode | O nó do elemento a ser definido como o nó atual. |
| Tipo | Descrição |
|---|---|
| vazio |
var xmlString = "<test>" +
" <one>" +
" <two att=\"xxx\">abcd1234</two>" +
" <three boo=\"yah\" att=\"yyy\">1234abcd</three>" +
" <two>another</two>" +
" </one>" +
" <number>1234</number>" +
"</test>";
var xmlDoc = new XMLDocument2();
xmlDoc.parseXML(xmlString);
//returns the root node of the document tree.
var rootNode = xmlDoc.getDocumentElement(); //returns org.w3c.dom.Element
// sets the root node as the current element
xmlDoc.setCurrentElement(rootNode);
XMLDocument2 com escopo - setEnableCDATAReporting (booleano habilitado)
Define se os nós são tratados como CDATA ou texto normal após a análise. A emissão de relatórios de CDATA está desativada por padrão.
Este método deve ser chamado com XMLDocument2 com escopo - parseXML(String xmlDoc).
Consulte também: XMLNode com escopo - isCDATANode().
| Nome | Tipo | Descrição |
|---|---|---|
| ativar | Booliano | Sinalizador que indica se os nós CDATA devem ser tratados como nós CDATA ou de texto normal. Valores válidos:
Padrão: falso |
| Tipo | Descrição |
|---|---|
| Nenhum(a) |
O exemplo a seguir mostra como o CDATA é analisado em um elemento com a emissão de relatórios de CDATA ativada. O resultado de content.getFirstChild() é um elemento que contém o valor de texto de outro. Este elemento contém internamente as informações que o identificam como um tipo CDATA. O resultado de content.getLastChild() é um elemento que contém o elementode valor de texto . Este elemento contém internamente as informações como um tipo de texto.
var xmlString = "<test>" +
" <one>" +
" <three boo=\"yah\" att=\"yyy\">1234abcd</three>" +
" <two><![CDATA[another]]>element</two>" +
" </one>" +
" <number>1234</number>"
"</test>";
var xmlDoc = new XMLDocument2();
xmlDoc.setEnableCDATAReporting(true); // Enable CDATA reporting
xmlDoc.parseXML(xmlString);
var content = xmlDoc.getFirstNode('/test/one/two');
gs.info(content.getFirstChild().getTextContent()); // prints "another"
gs.info(content.getLastChild().getTextContent()); // prints "element"
Saída:
another
element
anotherelement
anotherelementXMLDocument2 com escopo - setNamespaceAware (booleano ciente)
Quando definido como verdadeiro, o objeto XMLDocument2 processa o documento com namespaces XML.
Se você não definir isso, um documento XML com namespaces não será enumerado corretamente e uma pesquisa XPath falhará.
| Nome | Tipo | Descrição |
|---|---|---|
| ciente | Booliano | Quando verdadeiro, o objeto XMLDocument2 processa o documento com namespaces XML. |
| Tipo | Descrição |
|---|---|
| vazio |
XMLDocument2 com escopo - toString()
Retorna uma cadeia de caracteres que contém o XML.
| Nome | Tipo | Descrição |
|---|---|---|
| Nenhum |
| Tipo | Descrição |
|---|---|
| Cadeia de caracteres | Uma cadeia de caracteres que contém o XML. |
var xmlString = "<test>" +
" <one>" +
" <two att=\"xxx\">abcd1234</two>" +
" <three boo=\"yah\" att=\"yyy\">1234abcd</three>" +
" <two>another</two>" +
" </one>" +
" <number>1234</number>" +
"</test>";
var xmlDoc = new XMLDocument2();
xmlDoc.parseXML(xmlString);
gs.info(xmlDoc.toString());
<?xml version="1.0" encoding="UTF-8"?>
<test>
<one>
<two att="xxx">abcd1234</two>
<three att="yyy" boo="yah">1234abcd</three>
<two>another</two>
</one>
<number>1234</number>
</test>