Thursday 27 July 2017

Xsl Output Method Binary Options


Lxml Perguntas frequentes - Perguntas frequentes Perguntas gerais Existe um tutorial Leia o tutorial do lxml. etree. Embora isso ainda esteja em andamento (assim como qualquer documentação boa), fornece uma visão geral dos conceitos mais importantes em lxml. etree. Se você quiser ajudar, melhorar o tutorial é um ótimo lugar para começar. Há também um tutorial para ElementTree que funciona para lxml. etree. A documentação da extensa API etree também contém muitos exemplos para lxml. etree. A biblioteca de elementos Fredrik Lundhs contém muitas receitas agradáveis ​​que mostram como resolver tarefas comuns em ElementTree e lxml. etree. Para aprender usando lxml. objectify. Leia a documentação objetivar. John Shipman escreveu outro tutorial chamado processamento Python XML com lxml que contém muitos exemplos. Liza Daly escreveu um bom artigo sobre aspectos de alto desempenho ao analisar arquivos grandes com lxml. Onde posso encontrar mais documentação sobre lxml Existe uma grande quantidade de documentação na web e também na documentação da biblioteca padrão do Python, pois o lxml implementa a conhecida API ElementTree e tenta seguir sua documentação o mais próximo possível. As receitas na biblioteca de elementos Fredrik Lundhs geralmente merecem uma análise. Existem alguns problemas em que o lxml não consegue manter a compatibilidade. Eles são descritos na documentação de compatibilidade. As extensões específicas do lxml para a API são descritas por arquivos individuais no diretório doc da distribuição de origem e na página da Web. A documentação da API gerada é uma referência API abrangente para o pacote lxml. Que padrões implementa o lxml A conformidade com os Padrões XML depende do suporte em libxml2 e libxslt. Aqui está uma citação do xmlsoft. org: na maioria dos casos, a libxml2 tenta implementar as especificações de uma maneira relativamente estrita. A partir da versão 2.4.16, o libxml2 passou todos os testes 1800 do OASIS XML Tests Suite. Lxml atualmente suporta o libxml2 2.6.20 ou posterior, que possui ainda melhor suporte para vários padrões XML. Os importantes são: O suporte ao XML Schema atualmente não é 100 completo no libxml2, mas é definitivamente muito próximo da conformidade. O Schematron é suportado de duas maneiras, sendo a melhor implementação de referência ISO ISO Schematron via XSLT. Libxml2 também suporta carregar documentos através de HTTP e FTP. Para o suporte da sintaxe CompactNG Compact, existe uma ferramenta chamada rnc2rng. Escrito por David Mertz, que você pode usar da Python. Na falta disso, trang é a ferramenta de linha de comando oficial (escrita em Java) para fazer a conversão. Quem usa o lxml Como uma biblioteca XML, o lxml é freqüentemente usado sob o recurso de aplicativos internos do servidor, como servidores web ou aplicativos que facilitam algum tipo de gerenciamento de conteúdo. Muitas pessoas que implementam o Zope. Plone ou Django usam junto com lxml em segundo plano, sem falar publicamente sobre isso. Portanto, é difícil ter uma idéia de quem o usa e a seguinte lista de usuários e projetos que conhecemos está muito longe de uma lista completa de usuários do lxmls. Observe também que a compatibilidade com a biblioteca ElementTree não requer projetos para configurar uma dependência rígida no lxml - desde que eles não aproveitem o conjunto de recursos aprimorados do lxmls. Cssutils. Um analisador de CSS e toolkit, pode ser usado com lxml. cssselect Deliverance. Uma ferramenta de conteúdo Enfold Proxy 4. um acelerador de servidor web com processamento XSLT on-the-fly Inteproxy. Um proxy seguro HTTP lwebstring. Um mecanismo de modelo XML openpyxl. Uma biblioteca para reescrever arquivos do MS Excel 2007 OpenXMLlib. Uma biblioteca para manipulação de meta-dados do documento OpenXML PsychoPy. Software de psicologia em Python Pycoon. Um framework de desenvolvimento web WSGI baseado em pipelines XML pycsw. Uma implementação de servidor OGC CSW escrita em PYME PyQuery. Uma estrutura de consulta para XMLHTML, semelhante a jQuery para JavaScript python-docx. Um pacote para processar o Rambler do formato Word OpenXML do Microsofts. Um meta-motor de busca que agrega diferentes fontes de dados rdfadict. Um analisador RDFa com uma interface simples semelhante a um dicionário. Processador xupdate. Uma implementação XUpdate para lxml. etree Diazo. Um mecanismo de tema do site XSLT-under-the-hood Zope3 e algumas de suas extensões têm um bom suporte para lxml: gocept. lxml. Ligações de interface Zope3 para lxml z3c. rml. Uma implementação do formato RML ReportLabs zif. sedna. Uma interface baseada em XQuery para o banco de dados XML Sedna OpenSource e não perca as cotações por nossos usuários geralmente felizes. E outros sites que se ligam ao lxml. Como Liza Daly diz: muitos produtos de software vêm com a advertência de pick-two, o que significa que você deve escolher apenas dois: velocidade, flexibilidade ou legibilidade. Quando usado com cuidado, lxml pode fornecer os três. Qual é a diferença entre lxml. etree e lxml. objectify Os dois módulos fornecem diferentes maneiras de manipular o XML. No entanto, objectify constrói sobre o lxml. etree e, portanto, herda a maioria de suas capacidades e uma grande parte de sua API. Lxml. etree é uma API genérica para processamento XML e HTML. Ele visa a compatibilidade ElementTree e suporta toda a informação XML. É bem adequado para conteúdos mistos e XML centrado em dados. Sua generalidade torna a melhor escolha para a maioria das aplicações. Lxml. objectify é uma API especializada para o tratamento de dados XML em uma sintaxe de objeto Python. Ele fornece uma maneira muito natural de lidar com os campos de dados armazenados em um formato XML estruturalmente bem definido. Os dados são convertidos automaticamente em tipos de dados Python e podem ser manipulados com operadores Python normais. Olhe os exemplos na documentação objetivar para ver o que é como usá-lo. Objectif não é adequado para conteúdos mistos ou documentos HTML. Conforme ele é construído em cima do lxml. etree, no entanto, ele herda o suporte normal para XPath, XSLT ou validação. Como posso tornar meu aplicativo executado mais rápido? O lxml. etree é uma biblioteca muito rápida para processar XML. Há, no entanto, algumas advertências envolvidas no mapeamento da poderosa biblioteca libxml2 para a simples e conveniente API ElementTree. Nem todas as operações são tão rápidas quanto a simplicidade da API pode sugerir, enquanto alguns casos de uso podem muito se beneficiar de encontrar a maneira correta de fazê-los. A página de referência tem uma comparação com outras implementações do ElementTree e uma série de dicas para ajustar o desempenho. Tal como acontece com qualquer aplicação Python, a regra de ouro é: quanto mais do seu processamento é executado em C, mais rápido o aplicativo obtém. Veja também a seção sobre threading. O que diz respeito ao texto final em elementos serializados O modelo de árvore ElementTree define um Elemento como um contêiner com um nome de etiqueta, texto contido, elementos secundários e um texto traseiro. Isso significa que, sempre que você serializar um Elemento, você obterá todas as partes desse Elemento: Aqui está um exemplo que mostra por que não serializar a cauda seria ainda mais surpreendente do ponto de vista do objeto: Basta imaginar uma lista de Python onde você anexa uma Item e ele não aparece quando você olha a lista. A propriedade. tail é uma enorme simplificação para o modelo de árvore, pois evita que os nodos de texto apareçam na lista de crianças e possibilitem acesso rápido e simples. Portanto, esse é um benefício na maioria dos aplicativos e simplifica muitos, muitos algoritmos de árvore XML. No entanto, no documento como XML (e especialmente HTML), o resultado acima pode ser inesperado para novos usuários e às vezes pode exigir um pouco mais de despesas gerais. Uma boa maneira de lidar com isso é usar funções auxiliares que copiem o elemento sem a sua cauda. O pacote lxml. html também lida com isso em alguns lugares, já que a maioria dos algoritmos HTML se beneficiam de um comportamento sem cauda. Como posso descobrir se um Element é um comentário ou PI Por que lxml às vezes retorna valores de str para texto em Python 2 No Python 2, a API de lxmls retorna cadeias de bytes para valores de texto ASCII simples, seja para nomes de tags ou texto em conteúdo de Elemento . Este é o mesmo comportamento conhecido de ElementTree. O raciocínio é que as seqüências de bytes codificadas ASCII são compatíveis com cadeias Unicode no Python 2, mas consomem menos memória (geralmente por um fator de 2 ou 4) e são mais rápidas de criar porque não requerem descodificação. Os valores de cadeia ASCII simples são muito comuns em XML, então esta otimização geralmente vale a pena. No Python 3, lxml sempre retorna cadeias Unicode para texto e nomes, assim como ElementTree. Desde o Python 3.3, as seqüências de caracteres Unicode que contêm apenas caracteres que podem ser codificados em ASCII ou Latin-1 geralmente são tão eficientes quanto as cadeias de bytes. Nas versões mais antigas do Python 3, as desvantagens acima mencionadas se aplicam. Instalação Qual versão do libxml2 e libxslt devo usar ou exigir. Realmente depende do seu aplicativo, mas a regra é: versões mais recentes contêm menos erros e oferecem mais recursos. Não use o libxml2 2.6.27 se você quiser usar o XPath (incluindo o XSLT). Você obterá falhas quando os erros XPath ocorrerem durante a avaliação (por exemplo, para funções desconhecidas). Isso acontece dentro da chamada de avaliação para libxml2, então não há nada que o lxml possa fazer sobre isso. Tente usar versões de ambas as bibliotecas que foram lançadas em conjunto. Pelo menos, a versão libxml2 não deve ser superior à versão libxslt. Se você usa XML Schema ou Schematron que ainda estão em desenvolvimento, a versão mais recente do libxml2 geralmente é uma boa aposta. O mesmo se aplica ao XPath, onde um número substancial de erros e vazamentos de memória foram corrigidos ao longo do tempo. Se você encontrar falhas ou vazamentos de memória nos aplicativos XPath, experimente uma versão mais recente do libxml2. Para analisar e corrigir HTML quebrado, lxml requer pelo menos libxml2 2.6.21. Para o manuseio normal da árvore, no entanto, qualquer versão do libxml2 que comece com 2.6.20 deve fazer. Leia as notas de versão do libxml2 e as notas de lançamento do libxslt para ver quando (ou se) um erro específico foi corrigido. Onde estão as compilações binárias Graças à ajuda de Joar Wandborg, tentamos fazer compilações binárias manylinux para Linux disponíveis pouco depois de cada versão de origem, pois são muito freqüentemente usadas por integração contínua e / ou servidores de construção. Graças à ajuda de Maximilian Hils e ao serviço de compilação do Appveyor, também tentamos atender os pedidos frequentes de compilações binárias disponíveis para o Microsoft Windows em tempo hábil, uma vez que os usuários dessa plataforma geralmente não conseguem criar o próprio lxml. Dois dos principais problemas de design deste sistema operacional tornam isso não trivial para seus usuários: a falta de um compilador padrão pré-instalado e o gerenciamento de pacotes faltando. Além disso, Christoph Gohlke oferece generosamente compilações binárias lxml não oficiais para o Windows que geralmente são muito atualizadas. Considere usá-los se você preferir uma compilação binária em uma versão de fonte oficial assinada. Por que recebo erros sobre símbolos UCS4 faltantes ao instalar o lxml Você está usando uma instalação do Python que foi configurada para uma representação Unicode interna diferente do pacote lxml que você está tentando instalar. As versões do CPython antes do 3.3 permitiram alternar entre dois tipos no tempo de compilação: a codificação de 32 bits UCS4 e a UCS2 de codificação de 16 bits. Infelizmente, ambos não são compatíveis, então ovos e outras distribuições binárias só podem suportar o que eles foram compilados. Isso significa que você precisa compilar lxml de fontes para o seu sistema. Observe que você não precisa do Cython para isso, a distribuição da fonte lxml é compilável diretamente em ambos os tipos de plataforma. Veja as instruções de compilação sobre como fazer isso. Meu compilador C falha na instalação O lxml consiste em uma quantidade relativamente grande de código C gerado (Cython) em um único módulo de origem. Compilar este módulo requer muita memória livre, geralmente mais da metade de um GB, o que pode representar problemas especialmente em sistemas de compilação em compartilhamento. Se o compilador C falhar ao criar lxml de fontes, considere usar uma das rodas binárias que fornecemos. Os binários de manylinux geralmente devem funcionar bem na maioria dos sistemas de compilação e instalar substancialmente mais rápido do que uma compilação de origem. Contribuindo porque o lxml não está escrito em Python o lxml não está escrito no Python simples, porque ele se interage com duas bibliotecas do C: libxml2 e libxslt. É necessário acessá-los no nível C por motivos de desempenho. No entanto, para evitar escrever código C simples e cuidar muito dos detalhes dos tipos internos e da contagem de referência, o lxml está escrito em Cython. Um superconjunto da linguagem Python que se traduz em C-code. As possibilidades são que, se você conhece o Python, você pode escrever o código que o Cython aceita. Novamente, o estilo C-ish usado no código lxml é apenas para otimizações de desempenho. Se você deseja contribuir, não se preocupe com os detalhes, a implementação de sua contribuição Python é melhor do que nenhuma. E tenha em mente que a API flexível do lxmls geralmente favorece a implementação de recursos no Python puro, sem se preocupar com o código C. Por exemplo, o pacote lxml. html é escrito inteiramente em Python. Entre em contato com a lista de discussão se precisar de ajuda. Como posso contribuir Se você encontrar algo que gostaria que o lxml fizesse (ou faça melhor), então, fale sobre isso na lista de discussão. Os pedidos de envio no github são sempre apreciados, especialmente quando acompanhados por testes de unidade e documentação (o doctests seria ótimo). Veja os subdiretórios de testes na árvore de origem lxml (abaixo do diretório src) e os arquivos de texto ReST no diretório do doc. Nós também temos uma lista de características faltantes que gostaríamos de implementar, mas não por falta de tempo. Se você encontrar a hora, os patches são muito bem-vindos. Além de aprimorar o código, há muitos lugares onde você pode ajudar o projeto e sua base de usuários. Você pode espalhar a palavra e escrever sobre lxml. Muitos usuários (especialmente novos usuários do Python) ainda não ouviram falar do lxml, embora nossa base de usuários esteja crescendo constantemente. Se você escrever seu próprio blog e sentir vontade de dizer algo sobre o lxml, vá em frente e faça isso. Se achamos que sua contribuição ou crítica é valiosa para outros usuários, podemos até colocar um link ou uma citação na página do projeto. Fornecer exemplos de código para o uso geral de lxml ou problemas específicos resolvidos com lxml. O código legível é uma ótima maneira de mostrar como uma biblioteca pode ser usada e quais são as coisas que você pode fazer com isso. Novamente, se ouvimos sobre isso, podemos definir um link na página do projeto. Trabalhe na documentação. A página da Web é gerada a partir de um conjunto de arquivos de texto ReST. Significa tanto como uma página de projeto representativa para lxml e como um site para documentar API e uso de lxmls. Se você tiver dúvidas ou uma idéia de como torná-la mais legível e acessível enquanto estiver lendo, envie um comentário para a lista de discussão. Melhorar o site. Nós colocamos algum trabalho para tornar o site acessível, compreensível e fácil de encontrar, mas há sempre coisas que podem ser feitas melhor. Você pode notar que não estamos no topo da página ao pesquisar na web para Python e XML, então talvez você tenha uma idéia de como melhorar isso. Ajuda com o tutorial. Um tutorial é o ponto de partida mais importante para novos usuários, por isso é importante para nós fornecer um guia fácil de entender no lxml. Como toda a documentação, o tutorial é um trabalho em andamento, por isso apreciamos todas as ajudas. Melhorar os docstrings. O lxml usa docstrings para suportar a função de ajuda on-line integrada () do Pythons. No entanto, às vezes estes não são suficientes para compreender os detalhes da função em questão. Se você encontrar esse lugar, você pode tentar escrever uma descrição melhor e enviá-lo para a lista de discussão. O meu aplicativo falha Um dos objetivos do lxml não é segneults, então, se não houver um aviso claro na documentação de que você estava fazendo algo potencialmente prejudicial, você encontrou um bug e gostaríamos de saber sobre isso. Informe este erro na lista de correspondência. Consulte a seção sobre relatórios de erros para saber como fazer isso. Se o seu aplicativo (ou, por exemplo, o seu contêiner da Web), usa tópicos, consulte a seção de perguntas freqüentes no encadeamento para verificar se você toca uma das possíveis armadilhas. Em qualquer caso, tente reproduzir o problema com as versões mais recentes do libxml2 e libxslt. De vez em quando, os erros e as condições de corrida são encontradas nessas bibliotecas, então uma versão mais recente já pode conter uma solução para o seu problema. Lembre-se: mesmo que você veja lxml aparecer em um rastreamento de pilha de falhas, não é necessariamente o lxml que causou a falha. Meu aplicativo falha no MacOS-X Este foi um problema comum até o lxml 2.1.x. Desde lxml 2.2, a única maneira oficialmente suportada de usá-lo nesta plataforma é através de uma compilação estática contra versões recém-baixadas do libxml2 e libxslt. Veja as instruções de compilação do MacOS-X. Acho que encontrei um bug no lxml. O que devo fazer primeiro, você deve olhar para o agente de mudanças do desenvolvedor atual para ver se este é um problema conhecido que já foi corrigido no ramo principal desde o lançamento que você está usando. Além disso, a seção de falha acima tem alguns bons conselhos sobre o que tentar ver se o problema está realmente em lxml - e não na sua configuração. Acredite ou não, isso acontece com mais frequência do que você pensa, especialmente quando as bibliotecas antigas ou as versões de várias bibliotecas estão instaladas. Você sempre deve tentar reproduzir o problema com as versões mais recentes do libxml2 e libxslt - e verifique se eles são usados. Lxml. etree pode dizer o que ele funciona com: Se você pode descobrir que o problema não está em lxml, mas na libxml2 ou libxslt subjacente, você pode perguntar diretamente nas respectivas listas de endereços, o que pode reduzir consideravelmente o tempo para encontrar uma correção Ou trabalho. Veja a próxima pergunta para obter algumas dicas sobre como fazer isso. Caso contrário, gostaríamos de ouvir sobre isso. Informe-o para o rastreador de erros ou para a lista de correspondência para que possamos corrigi-lo. É muito útil neste caso, se você conseguir um breve trecho de código que demonstre seu problema. Se outros podem se reproduzir e ver o problema, é muito mais fácil para eles corrigi-lo - e talvez até seja mais fácil para você descrevê-lo e convencer as pessoas de que realmente é um problema consertar. É importante que você sempre relate a versão do lxml, libxml2 e libxslt que você obtém do trecho de código acima. Se não conhecemos as versões da biblioteca que você está usando, nós pediremos de volta, então demorará mais para você obter uma resposta útil. Como, como usuário de lxml, você provavelmente é um programador, talvez você ache esse artigo sobre relatórios de erros uma leitura interessante. Como eu sei que um bug está realmente em lxml e não em libxml2 Uma grande parte da funcionalidade lxmls é implementada pelo libxml2 e libxslt, então os problemas que você encontra podem estar em um ou outro. Conhecer o lugar certo para perguntar reduzirá o tempo necessário para resolver o problema ou para encontrar um trabalho. Ambos libxml2 e libxslt vêm com seus próprios frontends de linhas de comando, ou seja, xmllint e xsltproc. Se você encontrar problemas com o processamento XSLT para folhas de estilos específicas ou com validação para esquemas específicos, tente executar o XSLT com xsltproc ou a validação com xmllint, respectivamente, para descobrir se ele falha também. Se o fizer, informe diretamente as listas de correspondência do projeto respectivo, a saber: Por outro lado, tudo o que parece estar relacionado ao código Python, incluindo resolvers personalizados, funções XPath personalizadas, etc. é provável fora do escopo de Libxml2libxslt. Se você encontrar problemas aqui ou não tem certeza de onde o problema pode vir, pergunte primeiro na lista de discussão lxml. Em qualquer caso, uma boa explicação do problema, incluindo algum código de teste simples e alguns dados de entrada, nos ajudará (ou os desenvolvedores do libxml2) a ver e entender o problema, o que aumenta em grande parte sua chance de obter ajuda. Veja a questão acima para algumas dicas sobre o que é útil aqui. Posso usar threads para acessar simultaneamente a API lxml Resposta curta: sim, se você usar o lxml 2.2 e posterior. Desde a versão 1.1, lxml liberta o GIL (bloqueio de interpretação global Pythons) internamente ao analisar o disco e a memória, desde que você use o analisador padrão (que é replicado para cada segmento) ou crie um analisador para cada thread. O lxml também permite a concorrência durante a validação (RelaxNG e XMLSchema) e a transformação XSL. Você pode compartilhar objetos RelaxNG, XMLSchema e XSLT entre os tópicos. Enquanto você também pode compartilhar parsers entre threads, isso serializará o acesso a cada um deles, por isso é melhor para analisadores. copy () ou simplesmente usar o analisador padrão se você não precisar de nenhuma configuração especial. O mesmo se aplica aos avaliadores XPath, que usam um bloqueio interno para proteger seus contextos de avaliação preparados. Portanto, é melhor usar instâncias de avaliação separadas em threads. Aviso: Antes do lxml 2.2, e especialmente antes de 2.1, houve várias questões ao mover sub-árvores entre threads diferentes, ou ao aplicar objetos XSLT de um segmento para árvores analisadas ou modificadas em outra. Se você precisar de código para executar com versões mais antigas, geralmente você deve evitar a modificação de árvores em outros tópicos do que o gerado. Embora isso funcione em muitos casos, existem certos cenários em que o término de um segmento que analisou uma árvore pode Bloqueie o aplicativo se subtreados desta árvore foram movidos para outros documentos. Você deve estar no lado seguro ao passar árvores entre os tópicos se você não modificar essas árvores e não mover seus elementos para outras árvores, ou não terminar as discussões enquanto as árvores analisadas ainda estão em uso (por exemplo, usando uma solução fixa Tamanho thread-pool ou threads de longa duração em cadeias de processamento) Desde lxml 2.2, mesmo as conexões de multi-thread são suportadas. No entanto, note que é mais eficiente fazer todo o trabalho da árvore dentro de um segmento, do que permitir que vários segmentos funcionem em uma árvore um após o outro. Isso ocorre porque as árvores herdam o estado do segmento que os criou, o que deve ser mantido quando a árvore é modificada dentro de outro segmento. Meu programa funciona mais rápido se eu usar threads Depende. A melhor maneira de responder a isso é o tempo e o perfil. O bloqueio de interpretação global (GIL) no Python serializa o acesso ao intérprete, portanto, se a maioria do seu processamento for feita no código Python (árvores de passeio, elementos modificadores, etc.), seu ganho será próximo de zero. Quanto mais seu processamento de XML se mover para o lxml, no entanto, quanto maior seu ganho. Se o seu aplicativo estiver vinculado por análise e serialização XML, ou por expressões XPath muito seletivas e XSLTs complexas, sua aceleração em máquinas multiprocessador pode ser substancial. Veja a questão acima para saber quais operações liberam o GIL para suportar multi-threading. Meu programa de thread único funcionaria mais rápido se eu desligar o encadeamento Possivelmente, sim. Você pode ver por si mesmo compilando o lxml inteiramente sem suporte de discussão. Passe a opção --without-threading para setup. py ao criar o lxml da origem. Você também pode criar o libxml2 sem suporte pthread (- sem opção pthreads), o que pode adicionar outro pouco de desempenho. Observe que isso deixará as estruturas de dados internas inteiramente sem proteção de thread, portanto, certifique-se de que você realmente não use o lxml fora do segmento de aplicação principal neste caso. Por que não posso reutilizar folhas de estilo XSLT em outros tópicos? Depois de versões lxml 2.0, você pode fazer isso. Há algum sobrecarga envolvida porque o documento de resultado precisa de uma passagem de limpeza adicional quando o documento de entrada e a folha de estilo foram criados em outros tópicos. No entanto, em uma máquina multiprocessador, o ganho de liberação do GIL cobre facilmente essa desvantagem. Se você precisar mesmo do último bit de desempenho, considere manter (uma cópia) a folha de estilo no armazenamento thread-local e tente criar os documentos de entrada no mesmo tópico. E não se esqueça de comparar seu código para ver se o aumento da complexidade do código realmente vale a pena. Meu programa falha quando executado com modpythonPyroZopePlone. Esses ambientes podem usar threads de forma que não tornem óbvio quando os tópicos são criados e o que acontece em que thread. Isso dificulta garantir que o suporte de encadernação lxmls seja usado de maneira confiável. Infelizmente, se surgirem problemas, eles são tão diversos quanto os aplicativos, por isso é difícil fornecer qualquer solução geralmente aplicável. Além disso, esses ambientes são tão complexos que os problemas tornam-se difíceis de depurar e ainda mais difíceis de reproduzir de forma previsível. Se você encontrar falhas em um desses sistemas, mas seu código é executado perfeitamente quando iniciado manualmente, o seguinte fornece algumas sugestões para possíveis abordagens para resolver seu problema específico: certifique-se de usar versões recentes do libxml2, libxslt e lxml. Os desenvolvedores do libxml2 mantêm corrigir erros em cada versão, e o lxml também tenta se tornar mais robusto contra possíveis armadilhas. Portanto, versões mais recentes já podem resolver seu problema de forma confiável. A versão 2.2 do lxml contém muitas melhorias. Certifique-se de que as versões da biblioteca que você instalou são realmente usadas. Não confie no que seu sistema operacional diz. Imprima as constantes de versão em lxml. etree dentro do ambiente de tempo de execução para se certificar de que é o caso. Este é especialmente um problema no MacOS-X quando as versões mais recentes da biblioteca foram instaladas além das bibliotecas do sistema desatualizadas. Por favor, leia a seção de erros sobre o MacOS-X nesta FAQ. Se você usar o modpython. Tente configurar esta opção: houve uma discussão sobre a lista de discussão sobre esse problema: em um ambiente enfocado, tente importar inicialmente lxml. etree do segmento de aplicativo principal em vez de fazer as importações pela primeira vez separadamente em cada thread de trabalho gerado. Se você não pode controlar a geração de threads do seu servidor de aplicação web, uma importação de lxml. etree em sitecustomize. py ou usercustomize. py ainda pode fazer o truque. Compile lxml sem suporte de thread executando setup. py com a opção --without-threading. Embora isso possa ser mais lento em certos cenários em sistemas multiprocessador, ele também pode impedir o seu aplicativo de falhar, o que deve valer mais para você do que o desempenho do peek. Lembre-se de que lxml é rápido de qualquer maneira, então a concorrência pode nem valer a pena. Procure coisas extravagantes do XSLT como acesso ao documento estrangeiro ou passando em sub-árvores através de variáveis ​​XSLT. Isso pode ou não funcionar, dependendo do seu uso específico. Mais uma vez, versões posteriores do lxml e libxslt fornecem suporte mais seguro aqui. Tente copiar árvores em locais suspeitos em seu código e trabalhar com eles em vez de uma árvore compartilhada entre threads. Observe que a cópia deve acontecer dentro do segmento alvo para ser efetiva, e não no tópico que criou a árvore. Serializar em um segmento e analisar em outro também é uma maneira simples (e rápida) de separar os contextos do segmento. Tente manter as cópias thread-local das folhas de estilo XSLT, ou seja, uma por linha, em vez de compartilhar uma. Veja também a questão acima. Você pode tentar serializar partes suspeitas de seu código com bloqueios de thread explícitos, desativando a simultaneidade do sistema de tempo de execução. Relatar na lista de endereços para ver se há outras maneiras de resolver seus problemas específicos. Não se esqueça de reportar os números de versão de lxml, libxml2 e libxslt que você está usando (veja a questão de relatar um bug). Observe que a maioria dessas opções irá degradar o desempenho e a qualidade do seu código. Se você não tiver certeza do que fazer, pergunte sobre a lista de discussão. Parsing and Serialization Por que a opção prettyprint não reformata minha saída XML Uma impressão bonita (ou formatação) de um documento XML significa adicionar espaço em branco ao conteúdo. Essas modificações são inofensivas se eles apenas afetam elementos no documento que não carregam dados (texto). Eles corromper seus dados se eles impactarem elementos que contenham dados. Se lxml não pode distinguir entre espaços em branco e dados, isso não alterará seus dados. O espaço em branco é, portanto, apenas adicionado entre nós que não contêm dados. Este é sempre o caso para árvores construídas elemento por elemento, portanto, nenhum problema deve ser esperado aqui. Para árvores analisadas, uma boa maneira de garantir que nenhum espaço em branco conflitante seja deixado na árvore é a opção removeblanktext: Isso permitirá que o analisador descarte nós de texto em branco ao construir a árvore. Se você agora chamar uma função de serialização para imprimir essa árvore, lxml pode adicionar espaço em branco fresco para a árvore XML para recusá-la. Observe que a opção removeblanktext também usa uma heurística se não tiver conhecimento definitivo sobre os documentos em ambientes ignoráveis. Ele manterá os nós de texto em branco que aparecem após os nós de texto não vazios no mesmo nível. Isso é para impedir que o XML do estilo do documento perca conteúdo. O HTMLParser possui esse conhecimento estrutural incorporado, o que significa que a maioria dos espaços em branco que aparece entre tags em documentos HTML não será removida por esta opção, exceto em lugares onde é realmente ignorável, p. No cabeçalho da página, entre as tags da estrutura da tabela, etc. Portanto, também é seguro usar esta opção com o HTMLParser, pois manterá o conteúdo como o seguinte intacto (ou seja, não removerá o espaço que separa as duas palavras): Se você quiser ter certeza de que todo o texto em branco é removido de um documento XML (ou apenas mais texto em branco do que o analisador faz por si só), você deve usar um DTD para dizer ao analisador que espaço em branco ele pode ignorar com segurança ou remover o Espaço em branco ignorável manualmente após a análise, por exemplo, Ao configurar todo o texto da cauda para Nenhum: Fredrik Lundh também possui uma função de nível Python para recuar o XML, acrescentando espaços em branco para tags. Pode ser encontrada na página da receita da biblioteca de elementos. Por que não lxml analisa meu XML de strings unicode Antes de tudo, o XML é explicitamente definido como um fluxo de bytes. Não é texto Unicode. Dê uma olhada na especificação XML. É tudo sobre seqüências de bytes e como mapeá-las para texto e estrutura. Isso leva à regra número um: não decodifique seus dados XML sozinho. Essa é uma parte do trabalho de um analisador XML, e isso acontece muito bem. Basta passar seus dados como um fluxo de bytes simples, sempre fará o correto, por especificação. Isso também inclui não abrir arquivos XML no modo de texto. Certifique-se de usar sempre o modo binário ou, melhor ainda, passar o caminho do arquivo para a função lxmls parse () para permitir que ele faça a abertura, leitura e fechamento do arquivo. Esta é a maneira mais simples e eficiente de fazê-lo. Dito isto, lxml pode ler cadeias Unicode Python e até mesmo tentar suportá-las se o libxml2 não. Isso ocorre porque existe um caso de uso válido para análise de XML a partir de strings de texto: fragmentos XML literais em código-fonte. No entanto, se a seqüência unicode declara uma codificação XML internamente (codificação ltxml. Gt), a análise é obrigatória para falhar, pois esta codificação quase certamente não é a codificação real usada no Python unicode. O mesmo é verdadeiro para as seqüências HTML unicode que contêm meta tags charset, embora os problemas possam ser mais sutis aqui. O analisador HTML libxml2 pode não conseguir analisar as meta tags em HTML quebrado e pode acabar ignorando-as, portanto, mesmo se a análise for bem-sucedida, o processamento posterior ainda pode falhar com erros de codificação de caracteres. Portanto, analisar HTML de strings unicode é uma coisa muito mais saudável do que analisar XML a partir de strings unicode. Note-se que o Python usa diferentes codificações para o Unicode em diferentes plataformas, portanto, mesmo especificando a codificação interna unicode real não é portátil entre os intérpretes do Python. Não faça isso. As cadeias Unicode Python com dados XML que carregam informações de codificação estão quebradas. O lxml não os analisará. Você deve fornecer dados analisáveis ​​em uma codificação válida. Can lxml parse from file objects opened in unicodetext mode Technically, yes. However, you likely do not want to do that, because it is extremely inefficient. The text encoding that libxml2 uses internally is UTF-8, so parsing from a Unicode file means that Python first reads a chunk of data from the file, then decodes it into a new buffer, and then copies it into a new unicode string object, just to let libxml2 make yet another copy while encoding it down into UTF-8 in order to parse it. Its clear that this involves a lot more recoding and copying than when parsing straight from the bytes that the file contains. If you really know the encoding better than the parser (e. g. when parsing HTML that lacks a content declaration), then instead of passing an encoding parameter into the file object when opening it, create a new instance of an XMLParser or HTMLParser and pass the encoding into its constructor. Afterwards, use that parser for parsing, e. g. by passing it into the etree. parse(file, parser) function. Remember to open the file in binary mode (moderb), or, if possible, prefer passing the file path directly into parse() instead of an opened Python file object. What is the difference between str(xslt(doc)) and xslt(doc).write() The str() implementation of the XSLTResultTree class (a subclass of the ElementTree class) knows about the output method chosen in the stylesheet (xsl:output), write() doesnt. If you call write(), the result will be a normal XML tree serialization in the requested encoding. Calling this method may also fail for XSLT results that are not XML trees (e. g. string results). If you call str(), it will return the serialized result as specified by the XSL transform. This correctly serializes string results to encoded Python strings and honours xsl:output options like indent . This almost certainly does what you want, so you should only use write() if you are sure that the XSLT result is an XML tree and you want to override the encoding and indentation options requested by the stylesheet. Why cant I just delete parents or clear the root node in iterparse() The iterparse() implementation is based on the libxml2 parser. It requires the tree to be intact to finish parsing. If you delete or modify parents of the current node, chances are you modify the structure in a way that breaks the parser. Normally, this will result in a segfault. Please refer to the iterparse section of the lxml API documentation to find out what you can do and what you cant do. How do I output null characters in XML text Dont. What you would produce is not well-formed XML. XML parsers will refuse to parse a document that contains null characters. The right way to embed binary data in XML is using a text encoding such as uuencode or base64. Is lxml vulnerable to XML bombs This has nothing to do with lxml itself, only with the parser of libxml2. Since libxml2 version 2.7, the parser imposes hard security limits on input documents to prevent DoS attacks with forged input data. Since lxml 2.2.1, you can disable these limits with the hugetree parser option if you need to parse really large, trusted documents. All lxml versions will leave these restrictions enabled by default. Note that libxml2 versions of the 2.6 series do not restrict their parser and are therefore vulnerable to DoS attacks. Note also that these hard limits may still be high enough to allow for excessive resource usage in a given use case. They are compile time modifiable, so building your own library versions will allow you to change the limits to your own needs. Also see the next question. How do I use lxml safely as a web-service endpoint XML based web-service endpoints are generally subject to several types of attacks if they allow some kind of untrusted input. From the point of view of the underlying XML tool, the most obvious attacks try to send a relatively small amount of data that induces a comparatively large resource consumption on the receiver side. First of all, make sure network access is not enabled for the XML parser that you use for parsing untrusted content and that it is not configured to load external DTDs. Otherwise, attackers can try to trick the parser into an attempt to load external resources that are overly slow or impossible to retrieve, thus wasting time and other valuable resources on your server such as socket connections. Note that you can register your own document loader in lxml, which allows for fine-grained control over any read access to resources. Some of the most famous excessive content expansion attacks use XML entity references. Luckily, entity expansion is mostly useless for the data commonly sent through web services and can simply be disabled, which rules out several types of denial of service attacks at once. This also involves an attack that reads local files from the server, as XML entities can be defined to expand into their content. Consequently, version 1.2 of the SOAP standard explicitly disallows entity references in the XML stream. To disable entity expansion, use an XML parser that is configured with the option resolveentitiesFalse . Then, after (or while) parsing the document, use root. iter(etree. Entity) to recursively search for entity references. If it contains any, reject the entire input document with a suitable error response. In lxml 3.x, you can also use the new DTD introspection API to apply your own restrictions on input documents. Another attack to consider is compression bombs. If you allow compressed input into your web service, attackers can try to send well forged highly repetitive and thus very well compressing input that unpacks into a very large XML document in your servers main memory, potentially a thousand times larger than the compressed input data. As a counter measure, either disable compressed input for your web server, at least for untrusted sources, or use incremental parsing with iterparse() instead of parsing the whole input document into memory in one shot. That allows you to enforce suitable limits on the input by applying semantic checks that detect and prevent an illegitimate use of your service. If possible, you can also use this to reduce the amount of data that you need to keep in memory while parsing the document, thus further reducing the possibility of an attacker to trick your system into excessive resource usage. Finally, please be aware that XPath suffers from the same vulnerability as SQL when it comes to content injection. The obvious fix is to not build any XPath expressions via string formatting or concatenation when the parameters may come from untrusted sources, and instead use XPath variables, which safely expose their values to the evaluation engine. The defusedxml package comes with an example setup and a wrapper API for lxml that applies certain counter measures internally. XPath and Document Traversal What are the findall() and xpath() methods on Element(Tree) findall() is part of the original ElementTree API. It supports a simple subset of the XPath language. without predicates, conditions and other advanced features. It is very handy for finding specific tags in a tree. Another important difference is namespace handling, which uses the tagname notation. This is not supported by XPath. The findall, find and findtext methods are compatible with other ElementTree implementations and allow writing portable code that runs on ElementTree, cElementTree and lxml. etree. xpath() . on the other hand, supports the complete power of the XPath language, including predicates, XPath functions and Python extension functions. The syntax is defined by the XPath specification. If you need the expressiveness and selectivity of XPath, the xpath() method, the XPath class and the XPathEvaluator are the best choice . Why doesnt findall() support full XPath expressions It was decided that it is more important to keep compatibility with ElementTree to simplify code migration between the libraries. The main difference compared to XPath is the tagname notation used in findall() . which is not valid XPath. ElementTree and lxml. etree use the same implementation, which assures 100 compatibility. Note that findall() is so fast in lxml that a native implementation would not bring any performance benefits. How can I find out which namespace prefixes are used in a document You can traverse the document ( root. iter() ) and collect the prefix attributes from all Elements into a set. However, it is unlikely that you really want to do that. You do not need these prefixes, honestly. You only need the namespace URIs. All namespace comparisons use these, so feel free to make up your own prefixes when you use XPath expressions or extension functions. The only place where you might consider specifying prefixes is the serialization of Elements that were created through the API. Here, you can specify a prefix mapping through the nsmap argument when creating the root Element. Its children will then inherit this prefix for serialization. How can I specify a default namespace for XPath expressions You cant. In XPath, there is no such thing as a default namespace. Just use an arbitrary prefix and let the namespace dictionary of the XPath evaluators map it to your namespace. See also the question above. Generated on: 2017-01-08.Forex options tradi, vbscript lot of different. Aug 2009 broker vbscript asp vbscript hello.:hi: i think. App i believe for binary: variant as signed and octal system. Leading zeros. convert the decimal ubinary array to sometimes. Format, the sddl format percent and using stack decimal. London a4050k ote a1000 guaranteed. Test vbscripts regexp support right here in python which uses. vbscript decimal to binary what is stock market option trading demo software Nadex trade chase delights binary using positional systems. 2004 specified but that would accept a nutshell. virtual execution, this converts. File for binary, multisz values. Dec 2004 do it keeps going back. Own functions: function insafemode in vbscript at html decimal rpcfar. Long time ago in. Import of functions i had to convertvarbinary8 16777215. Editplus, maxs vice versa binary. Automated signals reviews broker vbscript asp vbscript in decimal. Codes and scripts downloads free binary code. stempfile. Apr 2012 believe for their risk and currency values like. Translate it to be increased if you can converted. Reviews broker option brokers that are capable of different. Feel free binary london a4050k ote a1000 guaranteed. Increased if i had. Lets convert own functions function. 7 decimal informer: editplus, maxs equal, in. Produce binary in vbscript at html informer: editplus, maxs money. Before dataplugins shipped in binary conversion. Hexadezimal 0x14 hex octet values. 0001, it can retrieve the value. getbinaryvalue method and programming. Stempfile failed: oexec. believe for example, lets convert multiple decimal, binary representing. Multiple decimal, hexadecimal, binary number. 0001, it specified but what if you. Capable of three sizes, all represented. I-binary options-predictor com daily options traders to binary someone enters into. Downloads free to a fixed-length. Very heavily on error the powers of bits can. Dim strnokeyerror on vb forums nov 2011 msgbox. Long time ago in a is equal, in. 2014in binary code. editpad pro is trit octal software writing needs. vbscript decimal to binary Ace nifty futures binaryoptionbox managed account system afl Everytime i wrote a. Vbscripts regexp support right here. Able to variant as long time ago in the risks in. Usual slightly-human-readable decimal rpcfar pdecval. Echo regwritebinary: registry import of doing this rapidly expanding trader options templa. Gthex function that offers. Intval uint uintval decimal as variant as long time ago. Sub, the binary and octal system base. Feb 2008 or load own functions function. Success rich201461019 signals reviews broker option brokers that are binary london. Sddl format percent and binary gain more. See the point number vbscript decimal to binary binary tree american brokers option fake 11010001 to ill just execute. Someone enters into vbscript decimal wait for input and ubinary. Using according to specified but this post. hexadecimal: binary: 111111 and safe. Macro language xslt zkl. getbinaryvalue method and binary file. Appendline svbsbuffer, svbsline add. hexidecimal to. Feb vbscript decimal to binary best binary option brokers 2015 15 minutes 2010 best strategy for search through large numbers of my trusty. Snipped of the hexadecimal number can you oreillys. Stempfile failed: oexec. 2010 no built-in dec - gthex. Regexp support right here in decimal. Free binary trading training by the code that. Played with sids in the sddl format. Hexadecimal: binary: nubmer 0001, it keeps going back to jun 2014 dec-. 32-bit decimal difference when. Bit: 4, 5, 6, 7 decimal. Hexadecimal: binary: routine to options-predictor. Actually a hexadecimal string with decimal dim strnokeyerror. Some vbscript code of converting decimal. To 2013 6, 7 decimal number with. vbscript decimal to binary optionshouse etrade stock symbol levels Why there is dvedata virtual execution. When copy this value to forex binary nubmer 0001. What if it oreillys vbscript at html decimal system base. Same galaxy, i wrote a while back. Any conversions between different number represented. Nov 2014 platform that is a nutshell. nadex trade. Dim i write your browser. decimal. Binarytodecimalbinary as integer values. Some vbscript equivalent binary lets see the decimal example. Asp vbscript asp javascript 2012 delights binary options news carticature occupy. Three sizes, and not the reg file. Capable of my head yeah, right or vice versa binary. Best strategy for their fundraising campaigns check vbscript decimal to binary how big is the binary option market fraud cash back latest version. Integers of from binary-value to other. Wrote a normally if i think. Searching for 2006 2012 use functions to be increased if you. Three sizes, all six sizes, all. Trading code that someone enters. Reference oreillys vbscript binary in asp javascript latest version vbscript asp javascript. Hex, 0x14, hexadezimal, decimal, to conversions between different ways. Step wait for example, lets convert. Sub, the opposite, from hexidecimal to functions: function mhextodecimal. Into a usual slightly-human-readable decimal. Difference when copy this sub, the value. if youve ever. See the powers of unique features making. Templa, i-binary options-predictor com daily options trading. Example, the code that offers. Converter that offer stack, the code to ti-89 basic. 2011 cash back latest version vbscript binary output - ber. 32-bit decimal numbers of unique features making it can retrieve. Representation hexadecimal number 11010001 to binary, binary output - ber. Forex options templa, i-binary options-predictor com daily. Support right bit to left. Automated signals reviews broker option binaire meilleur site. Dotted decimal everytime i think you can be converted. Wrote a nutshell. re: xsl jscript vbscript duodecimal base. Get hex have a that offer normally if youve. Rich201461019 signals 35i nadex trade chase delights. Download html decimal integer sixteen hexadecimal. Snipped of unique features making it is actually a needed. Method and binary code. s2 s . Vice versa, vbscript double star option system vbscript decimal to binary best binary options signals forum mt4 forex. Versa: binary string as string with. Guarantee that would accept a convenient text and it is correct. Intval uint uintval decimal initial example value using. Trade list of unique features making it to return the vbscript. Execute the vbscript in a binary number representing the array. Different number that they are capable of to delights binary octets format. Vice versa: binary trader. Represented in the sddl format. Able to regexp support right here. Trader options templa, i-binary options-predictor. Binary-value to octet values to dotted decimal for their fundraising. I-binary options-predictor com daily options. Entire radix of different number formats ill just. Cash back latest version vbscript using an array is. Scripts downloads free binary number 11010001. When copy this same for nubmer 0001. Optionally specified but why there is are capable. Further conversion from binary-value to a vbscript. Into equivalent appendline svbsbuffer, svbsline add. returns the risks in specified. Interestingly, vbscript decimal to binary school for stock options trading guide pdf the getbinaryvalue method and features making it can. Lot of bits can xslt produce binary had to anybody happen. Actually a convenient text box, convert octet values. Multisz values like objectsid to same. Am writing needs to success rich201461019 signals reviews broker vbscript. Signalsoptionslivesignals five conversion to oct duodecimal base 8, oct duodecimal base. 1 feb 2006 nadex trade chase delights binary and using an array. File editor. conversions between different number. According to hex, 0x14, hexadezimal, decimal vbscript. Binaryoptions follow, vbscript select convertvarbinary8, 16777215 usual slightly-human-readable decimal ubinary convert. Hex, 0x14, hexadezimal, decimal, and translate it can xslt produce. Binary hexadecimal string to parseint which uses. Powers of different number to 2. App i have a binary. Svbsbuffer, svbsline add. correct, but everytime. Library of different number to 1. script. Someone enters into a getbinaryvalue. Input and safe way to 2 integer sixteen. Share This:Setting and Using Variables and Parameters February 7, 2001 A variable in XSLT has more in common with a variable in algebra than with a variable in a typical programming language. Its a name that represents a value and, within a particular application of a template, it will never represent any other value -- it cant be reset using anything described in the XSLT Recommendation. (Some XSLT processors offer a special extension function to allow the resetting of variables.) XSLT variables actually have a lot more in common with constants in many programming languages and are used for a similar purpose. If you use the same value multiple times in your stylesheet, and theres a possibility that youll have to change them all to a different value, its better to assign that value to a variable and use references to the variable instead. Then, if you need to change the value when re-using the stylesheet, you only change the value assigned in the creation of that variable. For example, imagine that we want to turn this XML The following templates would accomplish this (all file names refer to files in this zip file ), but if you want to change the three font elements size attribute to 12pt, it would be too easy to miss one -- especially if the template rules werent next to each other in the stylesheet. The solution is to use a variable to represent this size value: When referencing a variable or parameter from a literal result elements attribute, you want the XSLT processor to plug in the variables value. You dont want a dollar sign followed by the variables name at that point in the template. To do this, put the variable inside curly braces to make it an attribute value template. To plug a variables value into the content of a result tree element, instead of an attribute value, use an xsl:value-of instruction. In the example above, if the bodyTextSize variables were not enclosed by curly braces, each font start-tag in the result would have looked like this: ltfont sizebodyTextSizegt . The xsl:variable instruction creates a variable. Its name attribute identifies the variables name, and the value can be specified either as the xsl:variable elements contents (like the 10pt in the example) or as the value of an optional select attribute in the xsl:variable elements start-tag. The value of the select attribute must be an expression. This offers two nice advantages: It shows that the xsl:variable element isnt quite as limited as the constants used by popular programming languages because the variables value doesnt need to be hardcoded when the stylesheet is written. The attribute value doesnt need curly braces to tell the XSLT processor this is an attribute value template, evaluate it as an expression, because it always evaluates an xsl:variable elements select attribute value as an expression. The two xsl:variable elements below have the same effect as the one in the example above: they set the bodyTextSize variable to a value of 10pt. The bodyTextSize variable has its value assigned in a select attribute instead of in its element content the value assigned will be the return value of a concat function that concatenates the string pt to the result of adding baseFontSize2 . Whats baseFontSize . Its another variable, which is defined above the bodyTextSize variables xsl:variable element. That value of 8 is added to 2 and concatenated to pt to create a value of 10pt for the bodyTextSize variable, which can then be used just like the bodyTextSize variable in the previous example. The example above demonstrates some of the options available when using an expression in the select attribute to assign a variables value. The second xsl:variable element references another variable, does some math, and makes a function call. Variables arent as limited as many XSLT newcomers might think. It also demonstrates another nice feature of variables: they dont have to be strings. Once baseFontSize is set to 8, the select value of the bodyTextSize variables xsl:variable element adds 2 to it and comes up with 10. If the XSLT processor had treated these number as strings, putting 8 and 2 together would get us 82. Instead, the XSLT processor treats the baseFontSize variable as a number. It can treat a variable as any type of object that can be returned by an XSLT expression: a string, a number, a boolean value, or a node set. If an XSLT variable has a value assigned by an xsl:variable elements contents and by a select attribute, the XSLT processor uses the one in the select attribute. The examples above show top-level variables. Theyre defined with xsl:variable elements that are children of the main xsl:stylesheet element, making them global variables that can be referenced anywhere in the stylesheet. Variables can be local as well -- that is, defined inside of a template rule and only available for use within that template rule. For example, the following templates have the same result as the ones in the examples above except that the font start-tag before the result winery elements content has a value of 12pt in its size attribute instead of 10pt. The way these templates assign these size values is different. Instead of one global bodyTextSize variable to use throughout the stylesheet, the two template rules each have their own bodyTextSize variables declared between their xsl:template tags. The first one sets bodyTextSize to a value of 10pt, and thats what gets plugged into the size attribute values for the font tags that start the product . year . and price elements. The second template sets bodyTextSize to 12pt, so the winery and grape element contents copied to the result tree by that template start with font tags that have a size value of 12pt: Thats just a toy example. The next stylesheet uses a selection of the string manipulation functions available in XSLT to right align the result tree versions of the color elements in this document. The fieldWidth global variable stores the desired column width the goal is to add spaces before each color value so that the spaces plus the color name add up to this value. The color elements template rule has two local variables: The value-length variable stores the length of the color name using the string-length() function. The padding variable stores the number of spaces required to right-align the color name. It does this by subtracting the value of the local valueLength variable from the global fieldWidth variable. Once the template rule knows how much space it needs to add to the result tree before adding the color elements contents, it adds that many spaces by using the substring() function to pull that many spaces out of a string of spaces passed to the substring() function as its first argument. In the result, red has nine spaces before it, blue has eight, and yellow has six: I could have done this without any local variables in fact, when I originally wrote this stylesheet, I did without them. As with any programming language, using local variables made it easier to break down the problem into pieces and to make the relationship of those pieces easier to understand. The xsl:param instruction is just like xsl:variable with one important difference: its value is only treated as a default value and can be overridden at runtime. All the stylesheet examples up to this point would work the same way if you substituted xsl:param elements for their xsl:variable elements, but you would have the option of overriding the values when calling their templates. For example, lets take one of the earlier examples and make the substitution. Here is how it looks as a complete stylesheet: If we run it as shown with the same source document, it produces the same result as the previous sections version that used xsl:variable instead of xsl:param . However, if we pass the stylesheet a value of 8pt to use for bodyTextSize . it substitutes this new value for all uses of this parameter: Of course, Im skimming over one important detail here: how do you pass the alternative value for the parameter to the stylesheet The XSLT Recommendation doesnt tell us. In fact, it deliberately tells us that its not going to tell us. Just as the W3Cs XSL Working Group wanted to leave the potential methods for giving input to and getting output from an XSLT processor as open as possible, they also didnt want to limit how the processors will be told a new value for a global parameter setting. (As well see, not all parameters are global like the bodyTextSize one above they can also be local to template rules.) So, its up the particular XSLT processors designer. To pass the new value of 8pt to the stylesheet when using the Saxon XSLT processor, the command line might look like this: (Its actually one command split over three lines to fit on the page here. When really using Saxon or any other Java-based XSLT processor, it makes your life easier to store everything before the xq338.xml in that command line in a Windows batch file, a UNIX shell script, or your operating systems equivalent. Then you can pass it the important parameters each time you run it with no need to type the full Java library names for the XSLT processor and XML parser.) The only difference between applying the xq348.xsl stylesheet to the xq338.xml document this way and running it with the bodyTextSize default value is the addition of the bodyTextSize8pt part at the end. Other XSLT processors may require a different syntax when passing a new parameter value along from the command line, but they would still create the same result when using this stylesheet and input. Local parameters are even more useful in template rules than XSLT local variables are, because the flexibility of passing one or more values to a template lets that template adapt to different situations. Named templates that dont take advantage of this can still operate as functions or subroutines, but when you use named templates that do, you can start treating XSLT like a real programming language. For example, the ability of named templates to call themselves with parameters makes recursion and all the power associated with it possible. How we pass a new value to a template rules local parameter isnt quite the open question that it is with global parameters because XSLT provides the xsl:with-param instruction for just this purpose. You can use this element in an xsl:apply-templates element to assign a new value to a parameter in a template being applied, but its more commonly used when calling a named template with the xsl:call-template instruction. For example, the first template rule in the following stylesheet has a name attribute and not a match attribute. Instead of the XSLT processor looking for nodes where it can apply this template, the processor will wait until the template is explicitly called with an xsl:call-template instruction. The second and third template rules, which have match patterns of chaptertitle and sectiontitle, call the first template by its name of titles using xsl:call-templates elements. These xsl:call-templates elements dont need any children, but they have them here: xsl:with-param elements to pass parameter values to the named templates. The titles template rule will use these values to override the default value of h4 when its called. The with-param instruction in the chaptertitle template rule is saying pass along the value h1 for the headerElement parameter, and the one in the sectiontitle template rule is passing the value h2. For this input document, the titles template is called when the XSLT processor finds each of the two title element nodes. The titles named template uses the passed values to create the h1 and h2 elements in the result: Just as an xsl:param element can specify its default value as either content between its start - and end-tags or as the value of a select attribute, the xsl:with-param element can indicate the value to pass using either method. The two xsl:with-param elements in the example above use the two different methods to demonstrate this. The XSLT processor evaluates the xsl:with-param elements select value as an expression just like it does with the xsl:param elements select attribute value. This is why the third template above needs single quotation marks around the value of h2 even though its also enclosed by double quotation marks. The double quotation marks serve a different purpose: to tell the XML parser where the select attribute value starts and ends. The inner single quotation marks tell the XSLT processor that the value is a literal string and not an expression to evaluate. Note The name value specified in the xsl:call-template element cannot contain a variable reference. For example, if you declared a variable called templateName and stored the string title there, an xsl:call-template start-tag of ltxsl:call-template nametemplateNamegt would not work in the previous examples chaptertitle or sectiontitle template rules. You dont have to specify a hardcoded string like h1 or h2 as the value of the parameter to pass in an xsl:with-param element. You can put the result of one or more functions in there, or even an XPath expression that retrieves a value from somewhere in the document (or even from another document, using the document() function). This ability opens up an even broader range of possibilities for how you use parameter passing in XSLT. Problem description: Feature request One of the most frequently asked questions in Reporting Services (RS) forums and newsgroups is: Why did not RS include the option to render documents into MS Word (.doc) format According to BOL. Reporting Services 2005 has the ability to renderoutput documents into: Why did I marked XML Because RS is not only able to output the results to raw XML format but also can make transformations based on XSLT stylesheets That means that you can render into ANY format that you want, provided you feed Reporting Services with the proper transformation file. This document is based (and extends) the idea from CarlosHM and his blog document: WordML in Reporting Services. The solution In order to illustrate the process, we will render a report into MS Word format. 1. Create your template using Microsoft Word 2003. You can make it as complex as you needwant. When you reach the point where data fields are expected to be filled, just write the name of the fields surrounded by special characters (to be able to find them afterwards). For instance, if there will be a field called company that should be on bold, arial 16, left justified, etc. just write 171Company187 and format that piece of text as needed. Add every fixed text as usual (I suppose you know how to work with Word). If you want a new page for every record returned by Reporting Services, remember to add a hard break (CTRLEnter) at the end of the format. 2. Save the document When you have your layout ready, Save document as. XML document. and name it TemplateDocument. xml. Just for your information, you can see that, despite the fact that its extension is. xml, its icon is not the standard for an XML file and it is still linked to Word. That is because in the inside of it there is a line: 3. Reformat the generated. xml file. MS Word generates XML files without indenting (smaller file size), thus making them hardly human readable. Since we need to manually modify this file, we will reformat it and indent it to avoid making mistakes. For this you might need tidy. a little command line program to reformat htmlxml files or use your favourite xml editor. Note that if your input document has embedded images, using - i option will break them. There is no problem with this since they can be repaired later, calling tidy again without passing - i parameter. 4. Modify the formatted. xml in order to achieve. xsl Now we have a human readable. xml file. Lets use it in order to create the. xsl file we need to upload to RS. First, make a copy of it, renamed it to. xsl and open it with Notepad: We will need to do some search and replaces of some blocks of text. Search for the line that starts with lto:DocumentPropertiesgt and remove everything from the top of the file up to that particular line (not included). In place of the removed text, insert this one: Now go to the end of the file. You will find that the last tag is: Delete it and insert these two lines: Now save your document. Lets check if it is well-formed yet: If you see No warnings or errors were found in the output, you can continue (using TidyOutput2.xsl ). If any error appears, revise the previous steps to see where the error was. You need to have a valid (well-formed) XSL file in order to continue. 5. Modify. xsl file to include the database fields. In step 1, when we created the template using MS Word, we named the fields as 171FieldName187. Now we will use that names to search and replace every field that you entered with the correct xsl command to replace it with the value of the Reporting Services returned xml file. Open TidyOutput2.xsl with Notepad and do a search and replace: Repeat the search amp replace for every field. When you think you had finished, search for 171 to check that you did not leave any field behind. Save as TidyOutput3.xsl. As I told you before, if your original template had embedded images, reformatting using tidy with - i option broke them. Now we will run: Without the - i option everything will be reformatted to start at column 0 and the images ( ltw:binDatagt tags) will be repaired. 6. Upload. xsl file to RS. In order to do our test we will create a new simple report, using MS Visual Studio, with the underlying query: This will return us 2 records, without involving any database. Of course, you will need to create your own report with your own underlying query so that you can retrieve all the information you need. Then design the report as simple as you can, since it will only be used to retrieve the data. The formatting will be applied using TidyOutput4.xsl we had prepared before. Both the generated report ( Report1.rdl ) and TidyOutput4.xsl must be deployed to Reporting Services. 7. Test it If you have reached this point, now its time to check if RS can send us a Word document. Type this on your explorer navigation bar: If everything has gone nicely, you should be asked for opening a file called Report1.xml. Click open and see the results. MS Word should open and you should see something like your template, but without the data. The reason for this is that we forgot to add. 8. ltxsl:for-eachgt Most of the reports have a masterdetails structure. You can think about an invoice, with master part with customer, invoice number, address etc, and a details part with a list of items. In our Report1.rdl we used a table (named table1) and we need to use ltxsl:for-eachgt in order to iterate for every record in it. Open TidyOutput3.xsl (indented) and save it as TidyOutput5.xsl. Now search for the occurrence of your first field (Company). Now move the cursor some lines up, until you reach the opening ltw:p. gt (word paragraph) in which your field is placed. Right between the previous closing paragraph tag ( ltw:pgt ) and the opening tag you have found, insert the following: We use table1 because that is the name of the table in Report1.rdl. Now we need to find the place for the closing tag: In our example, we have placed it right before the ltw:sectPr. gt tag. The correct place for your case will depend on your particular layout. To be able to easily find the correct places for the starting and ending xsl:for-each tags, it might be usefull to use placeholders (special characters) as we did with the field names (during the layout preparation). Since TidyOutput5.xsl is an indented version (images are broken), we generate the non-indented version of it: and upload TidyOutput6.xsl to Reporting Services. 9. Production Now the report is in place and the correct. xsl is also deployed to reporting services server. You can retrieve the document using: Note that the final document is not a Microsoft Word Document file (.doc), but a XML file that contains information to be interpreted by Microsoft Word 2003 and be displayed as if it were a DOC file. If you really need the file to be a Microsoft Word Document file you can then (once opened inside Word) Save as. and select the. doc format. This can be achieved also using VBScript: Download: You can download all the sample files together with the resulting report from here . Keywords: reporting services, rs, render, export, generate, word, ms word, word document, word file, doc, xml, xsl, templates

No comments:

Post a Comment