スキップしてメイン コンテンツに移動

投稿

ラベル(xml)が付いた投稿を表示しています

PHPのXMLReaderを使ったXMLの読み込み

はじめに PHPでXMLを読み込むには、通常はSimpleXMLElementを使えば十分です。 ただし、XMLが巨大でメモリを節約して処理する必要がある場合は、XMLのパーサーであるXMLReaderを使って処理する方法があります。 XMLReaderを使って読み込む際はXMLの構造をどうとらえるかによって、プログラムの書き方が変わるのと、毎回読み込みの方法をプログラムしなければならないのが欠点です。 今回は下記のサンプルXMLのproduct部分を読み込むXMLReaderのプログラムのサンプルを、XMLReaderの機能紹介も兼ねて、いくつか示します。 <?xml version="1.0" encoding="UTF-8"?> <products> <date type="1">20200414</date> <product> <maker>AMD</maker> <name>Ryzen 3400G</name> </product> <product> <maker>Intel</maker> <name>Core i9 9900K</name> </product> </products> サンプルプログラムでは、下記のPHPの配列形式を取得することを目標にします。 実際の用途ではXMLReaderを使ってXMLを読み込むと同時に、CSVファイルに出力するなどといった処理が考えられます。 この場合、メモリはXMLReader部分と、読み込み途中で一時的に保持しているデータのみで利用されるので、メモリの使用量は最低限に抑えることができます。 [ [ "maker"=> "AMD", "name"=> "Ryzen

PHPのlibxmlでのエラーの扱い方

PHPでXML形式のデータを扱うにはlibxmlライブライを使うことが一般的です。 libxml内でのエラー発生時の処理は、libxml_use_internal_errorsの設定で、下記の2通りの設定が可能です。 libxml_use_internal_errors(false): Exceptionとして投げる。 libxml_use_internal_errors(true): libxml_get_errors()で取得。※libxml_clear_errorsで事前にエラーをクリアしておく方が無難。 libxml_use_internal_errors(true)に設定して、Exceptionを発生させないようにする関数のサンプルを示します。 $excecutionに実際のXML処理を渡します。 function executeInLibXmlUseInternalErrors(callable $execution) { // 現在のlibxml_use_internal_errorsの設定を処理後に戻すために保存 $useErrors = libxml_use_internal_errors(); try {   libxml_clear_errors(); libxml_use_internal_errors(true); return $execution(); } finally{ // 処理が終わったらlibxml_use_internal_errorsの設定をもとに戻す libxml_use_internal_errors($useErrors); } } // 下記はXPathでDOMDodumentからXMLの要素を取得する場合の使用例です。 // XMLの処理中にもExceptionが発生しないので、プログラム内で処理することができます。 $xpath = '/xpath'; $file = '/path_to_xml_file'; $result = executeInLibXmlUseInternalErrors(function

XMLStarletを使ってLinuxのコマンドラインからXMLを操作

LinuxのコマンドラインからXMLを操作する際には、 XMLStarlet を使うと便利です。 ただし、複雑な処理を適用する場合は、素直にプログラミング言語で提供されているDOMやParserを使う方が良いと思います。 例えば、下記のコマンドを実行すると、特定のxpathにマッチした要素の数を数えることができます。 # selはxml documentへのクエリや検索を実行するためのオプション # -tはテンプレートを指定するためのオプションで、下記の例では、さらに-vで指定したxpathを実行するように命令しています。 xml sel -t -v &quote;count(/xml/table/row)&quote; data.xml オプションは色々あるので、公式ドキュメントを読んで色々試してみるのが近道かと思います。

Java: org.w3c.dom.Node to Formatted Xml String

package com.dukesoftware.xml; import java.io.StringWriter; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Node; public class XmlUtils { public static String toString(Node node) throws TransformerException { StringWriter writer = new StringWriter(); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(node), new StreamResult(writer)); return writer.toString(); } }

Encode Java Object to XML and Decode XML to Java Object

In current software development world, serializing object to some human readable format such as "XML", "JSON" is quite common. In this post I will show you a small code snippet for encoding Java Object to XML and decoding XML to Java Object only using Java Standard API. I think this approach is suitable if you need to quick and simple solution to encoding and decoding java object to XML string. Actually code is very simple. Please see the code below :) If you need to input or output XML to file, you should pass FileOutputStream or FileInputStream instead of ByteArrayOutputStream or ByteArrayInputStream. package com.dukesoftware.utils.xml; import java.beans.XMLDecoder; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; public class XMLUtils { public final static Object decodeToXML(String file) throws FileNotFoundException{ try(XMLDecoder decoder =

Treat XPath Only Using Library Provided by Java SDK

Have you ever treated XML only using library provided in Java SDK? I think many people use external library for treating XML in Java. To be honest, I would prefer to use JDom ;P But I think it's good thing to know how to treat XML only using Java SDK. I will show you small code snippet for treating XML especially from XPath usage. The classes you should remember for treating XML is: DocumentBuilderFactory DocumentBuilder Document XPathFactory XPath XPathExpression XPathConstants NodeList Node Oops, a bit quite too much. Anyway I will show you an example code for reading XML string and select nodes by XPath. package com.dulesoftware.xpath; import java.io.IOException; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax

C#: XPath and HtmlTextWriter Example

Hey guys!! This post show you how to use XPath in C#. I wrote program for formatting rss feed (xml) to html for its example. XPath in C# The simplest way is just creating XmlDocument and call SelectNodes method. var xmlString = "some xml string...." // create XmlDocment var doc = new XmlDocument(); doc.LoadXml(xmlString); // selecting nodes by xpath string doc.SelectNodes("/rss/channel/item"); RSS Xml to Html Example Okay here is a simple XPath example - converting rss xml to html. using System.IO; using System.Web.UI; using System.Web; namespace Utility { public class RSStoHtmlWriter : HTMLWriteHelper { private readonly string url; public RSStoHtmlWriter(string url) { this.url = url; } public override void WriteBody(HtmlTextWriter htmlWriter) { using (var reader = new XmlTextReader(url)) { // **** using XPath!! **** // As you n

C#: XML string to XmlDocument

I have wrote some utility methods for creating XmlDocument from XML string. public static class XMLUtils { // xml string to XmlDocument public static XmlDocument ToXmlDocument(this string xml) { var doc = new XmlDocument(); doc.LoadXml(xml); return doc; } // XmlReader to XmlDocument // XMLReader is useful for read xml data from url source public static XmlDocument ToXmlDocument(this XmlReader reader) { var doc = new XmlDocument(); doc.Load(reader); return doc; } // path to xml file to XmlDocument public static XmlDocument ReadFromPath( string path) { return ToXmlDocument(File.ReadAllText(path)); } }

ActionScript 3.0: Read catalog.xml

I have written reading catalog.xml program in ActionScript 3.0. I know my code is not perfect however I make my code public because I would like to help someone who would like to analyze catalog.xml... hope it helps :) In short the code is simply reading xml file. package utils.tool { public class CatalogXmlReader { // you should change the namespace based on flash version private static const NS:String = "http://www.adobe.com/flash/swccatalog/9"; public function CatalogXmlReader() { } public function create(xml:XML):SWCCatalog { var ns:Namespace = getDefaultNamespace(xml); if (!(ns.uri === NS)) throw new Error("Namespace is wrong"); var versions:XMLList = xml.child(new QName(ns, "versions")); var swcVersion:SWCVersions = new SWCVersions(); swcVersion.swcVersion = versions

XmlTextReaderの使い方

備忘録としてSystem.Xml.XmlTextReaderのサンプルを載せておきます。 public static void ReadXMLSample(string path) { for (XmlReader textReader = new XmlTextReader(path); textReader.Read(); textReader.MoveToElement()) { Console.WriteLine("==================="); Console.WriteLine("Name:" + textReader.Name); Console.WriteLine("Base URI:" + textReader.BaseURI); Console.WriteLine("Local Name:" + textReader.LocalName); Console.WriteLine("Attribute Count:" + textReader.AttributeCount); Console.WriteLine("Depth:" + textReader.Depth); Console.WriteLine("Node Type:" + textReader.NodeType); } }

XmlTextWriterの使い方

備忘録としてSystem.Xml.XmlTextWriterのサンプルを載せておきます。 pathにxmlファイルを作成して保存するC#のプログラムです。 public static void CreateXMLSample(string path) { XmlTextWriter writer = new XmlTextWriter(path, Encoding.Default); writer.WriteStartDocument(true); writer.WriteStartElement("root"); for (int i = 0; i < 3; i++) { writer.WriteStartElement("element"); writer.WriteStartAttribute("path"); writer.WriteValue(@"c:\temp\test.txt"); writer.WriteEndAttribute(); for (int j = 0; j < 3; j++) { writer.WriteStartElement("attr"); writer.WriteStartAttribute("type"); writer.WriteValue("integer"); writer.WriteEndAttribute(); writer.WriteStartAttribute("value"); writer.WriteValue(j); writer.WriteEndAttribute(); writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); }

XML/XSL関連リンク集

XSLについては公式ページが参考になると思います。 W3C の XSLのページ XMLの基本 XMLマスター:ベーシック 実力養成講座 XMLで遊ぼう EXSLT サンプルで覚える XSLTプログラミング XML -伸び縮みマークアップ言語- xslメモ たのしいXML XSLT2.0の感覚 Abbey Workshop さんの XML関連の記事 の XMLのノードの値をSplitする方法の記事 は秀逸です! Project xml-common