XML

XML

Extensible Markup Language (XML) is a flexible, structured document format that defines human- and machine-readable encoding rules.
Oral  Brekke

Oral Brekke

1669207200

How to Serialization of Java Objects to XML Using XMLEncoder/Decoder

Serialization of Java Objects to XML can be done using XMLEncoder, XMLDecoder. Java Object Serialization feature was introduced in JDK 1.1. Serialization transforms a Java object or graph of Java object into an array of bytes which can be stored in a file or transmitted over a network. It is a crucial concept to learn for earning your Java certification.

At a later time we can transform those bytes back into Java objects. All this is done using java.io.ObjectOutputStream and java.io.ObjectInputStream classes. ObjectOutputStream class provides methods to write primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream.

However, there are problems related to this approach of Serialization of Java objects. Some of them are listed below:

  • Logic that saves and restores serialized objects is based on the internal structure of the constituent classes. Any changes to those classes between the time the object was saved and when it was retrieved may cause the deserialization process to fail.
  • Versioning problems can occur. If you save an object using one version of the class, but attempt to deserialize it using a newer, different version of the class, deserialization might fail.

Rather than serializing Java objects to binary format we can serialize them to XML documents which is human readable.

Project Structure :

projectsturcture
XMLEncoder

java.beans.XMLEncoder works by cloning the object graph and recording the steps that were necessary to create the clone. This way XMLEncoder has a “working copy” of the object graph that mimics the steps XMLDecoder would take to decode the file. Let’s see how to serialize a Java object using XMLEncoder.

Given below is the DVD class which has a List<Movie> as a member.

public class DVD {	
	private List movies=new ArrayList();	
	public DVD(){}
	public List getMovies() {
		return movies;
	}
	public void setMovies(List movies) {
		this.movies = movies;
	}	
	public String toString(){
		String movies="";
		for(Movie movie:getMovies()){
			movies += movie.getName()+", ";
		}
		return movies; 
	}	
 }

Movie class has name, runtime, directors, released year and cast as members.

public class Movie {	
	private String name;
	private int runtime;
	private String directors;
	private int released; 
	private String cast;	
	public Movie(){}	

	public Movie(String name, int runtime, String directors,int released, String cast) {		
		this.name = name;
		this.runtime = runtime;
		this.directors = directors;
		this.released = released;
		this.cast = cast;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getRuntime() {
		return runtime;
	}
	public void setRuntime(int runtime) {
		this.runtime = runtime;
	}
	public String getDirectors() {
		return directors;
	}
	public void setDirectors(String directors) {
		this.directors = directors;
	}
	public int getReleased() {
		return released;
	}
	public void setReleased(int released) {
		this.released = released;
	}
	public String getCast() {
		return cast;
	}
	public void setCast(String cast) {
		this.cast = cast;
	}

}

We want to save DVD object which constitutes List<Movie>. Serializing a DVD object would require serialization of Movie objects also.

Serializing Object to XML 

SerializeToXML class has main method which creates four Movie objects. Put them into a List and then set that list as value for DVD instance. Once we have the object to be serialized we create an XMLEncoder instance, then we write that object and call the close method on the encoder instance.

public class SerializeToXML {	

	private static final String SERIALIZED_FILE_NAME="dvd.xml";

	public static void main(String args[]){

		Movie bourneIndentity=new Movie("The Bourne Identity",119,"Doug Liman",2002,"Matt Damon, Franka Potente");
		Movie bourneSupermacy=new Movie("The Bourne Supremacy",108,"Paul Greengrass",2004,"Matt Damon, Franka Potente, Joan Allen");
		Movie bourneUltimatum=new Movie("The Bourne Ultimatum",115,"Paul Greengrass",2007,"Matt Damon, Edgar Ramirez, Joan Allen");
		Movie bourneLegacy=new Movie("The Bourne Legacy",135,"Tony Gilroy",2012,"Jeremy Renner, Rachel Weisz, Edward Norton");

		List moviesList=new ArrayList();
		moviesList.add(bourneIndentity);
		moviesList.add(bourneSupermacy);
		moviesList.add(bourneUltimatum);
		moviesList.add(bourneLegacy);

		DVD bourneSeries=new DVD();
		bourneSeries.setMovies(moviesList);

		XMLEncoder encoder=null;
		try{
		encoder=new XMLEncoder(new BufferedOutputStream(new FileOutputStream(SERIALIZED_FILE_NAME)));
		}catch(FileNotFoundException fileNotFound){
			System.out.println("ERROR: While Creating or Opening the File dvd.xml");
		}
		encoder.writeObject(bourneSeries);
		encoder.close();

	}

}

On executing the SerializeToXML class it will serialize the java object to dvd.xml file (In Eclipse IDE you might have to refresh the project to see the newly created dvd.xml file)

< ?xml version="1.0" encoding="UTF-8"?>
< java version="1.7.0_75" class="java.beans.XMLDecoder">
 < object class="co.edureka.DVD" id="DVD0">
  < void property="movies">
   < void method="add">
    < object class="co.edureka.Movie">
     < void property="cast">
      < string>Matt Damon, Franka Potente< /string>
     < /void>
     < void property="directors">
      < string>Doug Liman< /string>
     < /void>
     < void property="name">
      < string>The Bourne Identity< /string>
     < /void>
     < void property="released">
      < int>2002< /int>
     < /void>
     < void property="runtime">
      < int>119< /int>
     < /void>
    < /object>
   < /void>
   < void method="add">
    < object class="co.edureka.Movie">
     < void property="cast">
      < string>Matt Damon, Franka Potente, Joan Allen< /string>
     < /void>
     < void property="directors">
      < string>Paul Greengrass< /string>
     < /void>
     < void property="name">
      < string>The Bourne Supremacy< /string>
     < /void>
     < void property="released">
      < int>2004< /int>
     < /void>
     < void property="runtime">
      < int>108< /int>
     < /void>
    < /object>
   < /void>
   < void method="add">
    < object class="co.edureka.Movie">
     < void property="cast">
      < string>Matt Damon, Edgar Ramirez, Joan Allen< /string>
     < /void>
     < void property="directors">
      < string>Paul Greengrass< /string>
     < /void>
     < void property="name">
      < string>The Bourne Ultimatum< /string>
     < /void>
     < void property="released">
      < int>2007< /int>
     < /void>
     < void property="runtime">
      < int>115< /int>
     < /void>
    < /object>
   < /void>
   < void method="add">
    < object class="co.edureka.Movie">
     < void property="cast">
      < string>Jeremy Renner, Rachel Weisz, Edward Norton< /string>
     < /void>
     < void property="directors">
      < string>Tony Gilroy< /string>
     < /void>
     < void property="name">
      < string>The Bourne Legacy< /string>
     < /void>
     < void property="released">
      < int>2012< /int>
     < /void>
     < void property="runtime">
      < int>135< /int>
     < /void>
    < /object>
   < /void>
  < /void>
 < /object>
< /java>

Deserializing Object from XML

To get the DVD object back from XML file we will use java.beans.Decoder class.

Original article source at: https://www.edureka.co/

#java #objects #xml 

How to Serialization of Java Objects to XML Using XMLEncoder/Decoder
Connor Mills

Connor Mills

1668238299

YAML vs JSON vs XML: Which One to Choose?

In this tutorial, you will learn how YAML compares to XML and JSON - two languages also used for creating configuration files. XML VS JSON VS YAML - What's The Difference?

YAML is one of the most popular languages for writing configuration files.

In this article, you will learn how YAML compares to XML and JSON - two languages also used for creating configuration files.

You will also learn some of the rules and features of the language, along with its basic syntax.

Here is what we will cover:

  1. What is YAML?
  2. XML VS JSON VS YAML - What's The Difference?
    1. XML
    2. JSON
    3. YAML
  3. Features and basic rules of YAML
    1. How to create a YAML file
    2. Multi-document support in YAML
    3. Indentation in YAML
    4. Tabs in YAML
    5. Whitespace in YAML
    6. Explicit data types in YAML
  4. An introduction to YAML syntax
    1. Scalars
    2. Collections

What is YAML?

YAML stands for YAML Ain't Markup Language, but it originally stood for Yet Another Markup Language.

YAML is a human-readable data serialization language, just like XML and JSON.

Serialization is a process where one application or service that has different data structures and is written in a different set of technologies can transfer data to another application using a standard format.

In other words, serialization is about translating, converting, and wrapping up a data structure in another format.

The data in the new format can be stored in a file or transmitted to another application or service over a network.

YAML is a widely used format for writing configuration files for different DevOps tools, programs, and applications because of its human-readable and intuitive syntax.

XML VS JSON VS YAML - What's The Difference?

XML, JSON, and YAML are all used for creating configuration files and transferring data between applications.

Each language has its advantages and disadvantages.

Now, let's see some of the characteristics of the three languages. You will also see an example of how the same code is written in each language to demonstrate the high-level differences in their syntax.

XML

XML, which stands for Extensible Markup Language, was first introduced in 1996 and was designed for general-purpose use.

XML is a generalized markup language. It offers a structured yet flexible syntax and a defined document schema. This makes it a good choice when working with complex configurations that require a structured format and finer control over schema validation to ensure configurations always have the correct format.

With that said, XML's syntax can be verbose, redundant, and harder to read in comparison with other serialization languages.

<Employees>
    <Employee> 
        <name> John Doe </name>
        <department> Engineering </department>
        <country> USA </country>
    </Employee>
     <Employee> 
        <name> Kate Kateson </name>
        <department> IT Support </department>
        <country> United Kingdom </country>
    </Employee>
</Employees>

JSON

JSON stands for JavaScript Object Notation and has been around since the early 2000s.

JSON was initially inspired by the JavaScript programming language, but it is not tied to only one language. Instead, it is a language-independent format.

Most modern programming languages have libraries for parsing and generating JSON data.

JSON offers a much more readable, human-friendly, compact, and simple syntax compared to XML. It makes for a great format for storing and transferring information between web applications and servers over a network.

With that said, it may not offer the best support for complex configurations.

{
	"Employees": [
    {
			"name": "John Doe",
			"department": "Engineering",
			"country": "USA"
		},

		{
			"name": "Kate Kateson",
			"department": "IT support",
			"country": "United Kingdom"
		}
	]
}

YAML

YAML, originally known as Yet Another Markup Language, was created in 2001 but now stands for YAML Ain't Markup Language.

YAML is an official strict superset of JSON despite looking very different from JSON.

YAML can do everything that JSON can and more. A valid YAML file can contain JSON, and JSON can transform into YAML.

YAML has the most human-readable, intuitive, and compact syntax for defining configurations compared to XML and JSON.

YAML uses indentation to define structure in the file, which is helpful if you are used to writing Python code and are familiar with the indentation style the language uses.

With that said, if you don't get the indentation and format right, it can lead to validation errors, making it not the friendliest for beginners.

Employees:
- name: John Doe
  department: Engineering
  country: USA
- name: Kate Kateson
  department: IT support
  country: United Kingdom

Features and Basic Rules of YAML

Now, let's go over some of the basic rules and features of the language.

How to Create a YAML File

To create a YAML file, use either the .yaml or .yml file extension.

Multi-Document Support in YAML

Before writing any YAML code, you can add three dashes (---) at the start of the file:

---
Employees:
- name: John Doe
  department: Engineering
  country: USA
- name: Kate Kateson
  department: IT support
  country: United Kingdom

YAML allows you to have multiple YAML documents in a singe YAML file, making file organization much easier.

Separate each document with three dashes (---):

---
Employees:
- name: John Doe
  department: Engineering
  country: USA
- name: Kate Kateson
  department: IT support
  country: United Kingdom
---
Fruit:
 - Oranges
 - Pears
 - Apples

You can also use three dots (...) to mark the end of the document:

---
Employees:
- name: John Doe
  department: Engineering
  country: USA
- name: Kate Kateson
  department: IT support
  country: United Kingdom
...

Indentation in YAML

In YAML, there is an emphasis on indentation and line separation to denote levels and structure in data. The indentation system is quite similar to the one Python uses.

YAML doesn't use symbols such as curly braces, square brackets, or opening or closing tags - just indentation.

Tabs in YAML

YAML doesn't allow you to use any tabs when creating indentation - use spaces instead.

Whitespace in YAML

Whitespace doesn't matter as long as child elements are indented inside the parent element.

How to Write A Comment in YAML

To add a comment to comment out a line of code, use the # character:

---
# Employees in my company
Employees:
- name: John Doe
  department: Engineering
  country: USA
- name: Kate Kateson
  department: IT support
  country: United Kingdom

Explicit Data Types in YAML

Although YAML auto-detects the data types in a file, you can specify the type of data you want to use.

To explicitly specify the type of data, use the !! symbol and the name of the data type before the value:

# parse this value as a string
date: !!str 2022-11-11

## parse this value as a float (it will be 1.0 instead of 1)
fave_number: !!float 1

An Introduction to YAML Syntax

Scalars

Scalars in YAML are the data on the page - strings, numbers, booleans, and nulls.

Let's see some examples of how to use each one.

In YAML, strings in some cases can be left unquoted, but you can also wrap them in single (' ') or double (" ") quotation marks:

A string in YAML!

'A string in YAML!'

"A string in YAML!"

If you want to write a string that spans across multiple lines and you want to preserve the line breaks, use the pipe symbol (|):

|
 I am message that spans multiple lines
 I go on and on across lines
 and lines
 and more lines

Make sure that the message is indented!

Alternatively, if you have a string in a YAML file that spans across multiple lines for readability, but you want the parser to interpret it as a single line string, you can use the > character, which will replace each line break with a space:

>
 I am message that spans
 multiple lines
 but I will be parsed
 on one line

Again, make sure you don't forget to indent the message!

Numbers express numerical data, and in YAML, these include integers (whole numbers), floats (numbers with a decimal point), exponentials, octals, and hexadecimals:

# integer
19

# float 
8.7

# exponential
4.5e+13

# octal 
0o23

# hexadecimal
0xFF

Booleans in YAML, and other programming languages, have one of two states and are expressed with either true or false.

Words like true and false are keywords in YAML, so don't surround them with quotation marks if you want them interpreted as booleans.

Lastly, Null values are expressed with the keyword null or the tilde character, ~.

Collections

More often than not, you will not be writing simple scalars in your YAML files - you will be using collections instead.

Collections in YAML can be:

  • Sequences (lists/arrays)
  • Mappings (dictionaries/hashes)

To write a sequence, use a dash (-) followed by a space:

- HTML
- CSS
- JavaScript

Each item in the sequence (list) is placed on a separate line, with a dash in front of the value.

And each item in the list is on the same level.

That said, you can create a nested sequence (remember, use spaces - not tabs - to create the levels of indentation):

- HTML
- CSS
- JavaScript
 - React
 - Angular
 - Vue

In the sequence above, React, Angular and Vue are sub-items of the item JavaScript.

Mappings allow you to list keys with values. Key/value pairs are the building blocks of YAML documents.

Use a colon (:) followed by a space to create key/value pairs:

Employees:
 name: John Doe
 age: 23
 country: USA

In the example above, a name gets assigned to a specific value.

The value John Doe gets mapped (or assigned) to the name key, the value 23 gets mapped to the age key, and the value USA gets mapped to the country key. Altogether, these create an object.

You can also use a mapping with a sequence.

For example, taking the example sequence from earlier on, here is how you would build a list of frontend_languages:

frontend_languages:
 - HTML
 - CSS
 - JavaScript
  - React
  - Angular
  - Vue

In the example above, I created a list of frontend_languages, where there are multiple values under the same key, frontend_languages.

Similarly, you can create a list of objects:

Employees:
- name: John Doe
  department: Engineering
  country: USA
- name: Kate Kateson
  department: IT support
  country: United Kingdom

Conclusion

Hopefully, this article was helpful and gave you insight into what YAML is, what the syntax of the language looks like, and how it differs from XML and JSON.

Thank you for reading, and happy coding!

Original article source at https://www.freecodecamp.org

#yaml #json #xml 

YAML vs JSON vs XML: Which One to Choose?
Toby Rogers

Toby Rogers

1666940978

3 Ways to Open an XML File

XML stands for eXtensible Markup Language. XML files are readable files that describe the structure of data. You store XML files with the .xml extension.

An XML file contains tags that specify how the document should be structured and how it should be stored and transmitted over the internet.

It is no longer the preferred method for organizing and transmitting data, but many legacy systems still use it. Also, both RSS and SVG are based on the XML format.

This is how XML appears:

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
   <book id="bk1">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
   </book>
   <book id="bk2">
      <author>Corets, Eva</author>
      <title>Oberon's Legacy</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
   </book>
   <book id="bk3">
      <author>Corets, Eva</author>
      <title>The Sundered Grail</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
   </book>
</catalog>

In this article, you will learn the various ways you can open an XML file, either on your computer or online.

  1. How to Open an XML File Using a Text Editor
  2. How to Open an XML File Using a Browser
  3. How to Open an XML File Online

How to Open an XML File Using a Text Editor

You must have an XML file you are trying to open, either to view only or to view and edit.

If you want to open an XML file and edit it, you can use a text editor. You can use default text editors, which come with your computer, like Notepad on Windows or TextEdit on Mac.

All you have to do is locate the XML file, right-click the XML file, and select the "Open With" option. This will display a list of programs to open the file.

s_6918DB109E81C99C403FDE441785C55AA8E56E1977270D55F040260DC7FE989F_1666877244802_image

Select Notepad if it is a Windows computer or TextEdit if it is a Mac computer, as shown in the image above. These two are pre-installed text editors for each operating system and should already be on the list. Any basic text editor will work.

You can use other text editors like VSCode (which is suggested on the image above), Atom, Sublime Text and others. But it is always best to use default editors for basic tasks like this, as text editors like VSCode, Atom, and Sublime Text are pretty heavy programs.

How to Open an XML File Using a Browser

If you only want to view the file, you can use any web browser such as Safari, Chrome, and lots more with similar procedures.

The first step is to locate the XML file you want to open, right-click the file, and select the “open with” option. A list of options will appear, including some browsers.

s_6918DB109E81C99C403FDE441785C55AA8E56E1977270D55F040260DC7FE989F_1666878064357_image

Click on your preferred browser, and then your XML will load up.

Another option would be to open your browser and then drag the XML file to the browser. This also works for text editors.

How to Open an XML File Online

On the internet, dozens of XML viewers and even converters help convert XML files to other formats like JSON. Here are some of the most popular online XML viewers/editors:

Each one works similarly, allowing you to upload the XML file from your computer.

Chrome has an XML Viewer extension, which works like all these online XML viewers. All you have to do is download the extension. Then click on it whenever you want to open an XML file.

s_6918DB109E81C99C403FDE441785C55AA8E56E1977270D55F040260DC7FE989F_1666878537071_image

Once you click on it, an interface that is easy to navigate will appear with two major options you can use to upload your XML file: From your PC or From your Google Drive.

s_6918DB109E81C99C403FDE441785C55AA8E56E1977270D55F040260DC7FE989F_1666878607944_image

When you select an option, you can search for the file, and within a few milliseconds, your XML file will open in the plain section.

s_6918DB109E81C99C403FDE441785C55AA8E56E1977270D55F040260DC7FE989F_1666878725496_image

Ta-da 😂

In this short article, you have learned how to open an XML file. I hope this will help you.

Have fun coding!

Original article source at https://www.freecodecamp.org

#xml

3 Ways to Open an XML File
Rupert  Beatty

Rupert Beatty

1666834800

Kanna: Kanna is an XML/HTML Parser for Swift

Kanna(鉋)

Kanna(鉋) is an XML/HTML parser for cross-platform(macOS, iOS, tvOS, watchOS and Linux!).

It was inspired by Nokogiri(鋸).

ℹ️ Documentation

Features

  •  XPath 1.0 support for document searching
  •  CSS3 selector support for document searching
  •  Support for namespaces
  •  Comprehensive test suite

Installation for Swift 5

CocoaPods

Add the following to your Podfile:

use_frameworks!
pod 'Kanna', '~> 5.2.2'

Carthage

Add the following to your Cartfile:

github "tid-kijyun/Kanna" ~> 5.2.2

For xcode 11.3 and earlier, the following settings are required.

In the project settings add $(SDKROOT)/usr/include/libxml2 to the "header search paths" field

Swift Package Manager

Installing libxml2 to your computer:

// macOS: For xcode 11.3 and earlier, the following settings are required.
$ brew install libxml2
$ brew link --force libxml2

// Linux(Ubuntu):
$ sudo apt-get install libxml2-dev
  1. Add the following to your Package.swift:
// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "YourProject",
    dependencies: [
        .package(url: "https://github.com/tid-kijyun/Kanna.git", from: "5.2.2"),
    ],
    targets: [
        .target(
            name: "YourTarget",
            dependencies: ["Kanna"]),
    ]
)
$ swift build

Note: When a build error occurs, please try run the following command:

// Linux(Ubuntu)
$ sudo apt-get install pkg-config

Manual Installation

  1. Add these files to your project:
    Kanna.swift
    CSS.swift
    libxmlHTMLDocument.swift
    libxmlHTMLNode.swift
    libxmlParserOption.swift
    Modules
  2. In the target settings add $(SDKROOT)/usr/include/libxml2 to the Search Paths > Header Search Paths field
  3. In the target settings add $(SRCROOT)/Modules to the Swift Compiler - Search Paths > Import Paths field

Installation for swift 4

Installation for swift 3

Synopsis

import Kanna

let html = "<html>...</html>"

if let doc = try? HTML(html: html, encoding: .utf8) {
    print(doc.title)
    
    // Search for nodes by CSS
    for link in doc.css("a, link") {
        print(link.text)
        print(link["href"])
    }
    
    // Search for nodes by XPath
    for link in doc.xpath("//a | //link") {
        print(link.text)
        print(link["href"])
    }
}
let xml = "..."
if let doc = try? Kanna.XML(xml: xml, encoding: .utf8) {
    let namespaces = [
                    "o":  "urn:schemas-microsoft-com:office:office",
                    "ss": "urn:schemas-microsoft-com:office:spreadsheet"
                ]
    if let author = doc.at_xpath("//o:Author", namespaces: namespaces) {
        print(author.text)
    }
}

Download Details:

Author: Tid-kijyun
Source Code: https://github.com/tid-kijyun/Kanna 
License: MIT license

#swift #html #xml 

Kanna: Kanna is an XML/HTML Parser for Swift
Zak Dyer

Zak Dyer

1666150578

Parsing and Modifying XML in Python

In this Python XML tutorial, you'll learn how to parse and modify XML in Python. Python enables you to parse and modify XML documents. In order to parse XML document, you need to have the entire XML document in memory.

What is XML?

XML stands for eXtensible Markup Language. It was designed to store and transport small to medium amounts of data and is widely used for sharing structured information.

Python enables you to parse and modify XML documents. In order to parse XML document, you need to have the entire XML document in memory.

XML stands for Extensible Markup Language. It was designed to store and transport data. It was designed to be both human- and machine-readable. That’s why, the design goals of XML emphasize simplicity, generality, and usability across the Internet.

Here we consider that the XML file is present in the memory. Please read the comments in the code for a clear understanding.

XML File:

python-parse-xml

Let us save the above XML file as “test.xml”. Before going further you should know that in XML we do not have predefined tags as we have in HTML. While writing XML the author has to define his/her own tags as well as the document structure. Now we need to parse this file and modify it using Python. We will be using “minidom” library of Python 3 to do the above task. This module does not come built-in with Python. To install this type the below command in the terminal.

pip install minidom

Reading XML

First we will be reading the contents of the XML file and then we will learn how to modify the XML file.
Example

import xml.dom.minidom as md

def main():

	# parsing the xml file and
	# storing the contents in
	# "file" object Put in the
	# path of your XML file in
	# the parameter for parse() method.
	file = md.parse( "test.xml" )

	# nodeName returns the type of
	# the file(in our case it returns
	# document)
	print( file.nodeName )

	# firstChild.tagName returns the
	# name of the first tag.Here it
	# is "note"
	print( file.firstChild.tagName )

	firstname = file.getElementsByTagName( "fname" )

	# printing the first name
	print( "Name: " + firstname[ 0 ].firstChild.nodeValue )

	lastname = file.getElementsByTagName( "lname" )

	# printing the last name
	print( "Surname: " + lastname[ 0 ].firstChild.nodeValue )

	favgame = file.getElementsByTagName( "favgame" )

	# printing the favourite game
	print( "Favourite Game: " + favgame[ 0 ].firstChild.nodeValue )

	# Printing tag values having
	# attributes(Here tag "player"
	# has "name" attribute)
	players = file.getElementsByTagName( "player" )

	for player in players:
		print( player.getAttribute( "name" ) )

if __name__=="__main__":
	main();

Output:

#document
note
Name: Jack
Surname: Shelby
Favourite Game: Football
Messi
Ronaldo
Mbappe

In the above Python code while printing First Name or Last Name we have used firstname[0] / lastname[0]. This is because there is only 1 “fname” and only 1 “lname” tag. For multiple same tags we can proceed like below.
XML:

python-parse-xml-2

Python

import xml.dom.minidom as md

def main():

	file = md.parse( "test.xml" )
	names = file.getElementsByTagName( "fname" )

	for name in names:

		print( name.firstChild.nodeValue )

if __name__=="__main__":
	main();

Output

Jack
John
Harry

Modifying XML

Now we have got a basic idea on how we can parse and read the contents of a XML file using Python. Now let us learn to modify an XML file.
XML File:

python-parse-xml-3

Let us add the following :

  • Height
  • Languages known by Jack

Let us delete the “hobby” tag. Also let us modify the age to 29.
Python Code:(Modifying XML)

import xml.dom.minidom as md

def main():

	file = md.parse("test.xml")
	
	height = file.createElement( "height" )

	# setting height value to 180cm
	height.setAttribute("val", "180 cm")

	# adding height tag to the "file"
	# object
	file.firstChild.appendChild(height)

	lan = [ "English", "Spanish", "French" ]

	# creating separate "lang" tags for
	# each language and adding it to
	# "file" object
	for l in lan:
		
		lang = file.createElement( "lang" )
		lang.setAttribute( "lng", l )
		file.firstChild.appendChild( lang )

	delete = file.getElementsByTagName( "hobby" )

	# deleting all occurences of a particular
	# tag(here "hobby")
	for i in delete:

		x = i.parentNode
		x.removeChild( i )

	# modifying the value of a tag(here "age")
	file.getElementsByTagName( "age" )[ 0 ].childNodes[ 0 ].nodeValue = "29"

	# writing the changes in "file" object to
	# the "test.xml" file
	with open( "test.xml", "w" ) as fs:

		fs.write( file.toxml() )
		fs.close()

if __name__=="__main__":
	main();

Output:

python-parse-xml-4

The last 3 lines of the Python code just converts the “file” object into XML using the toxml() method and writes it to the “test.xml” file. If you do not want to edit the original file and just want to print the modified XML then replace those 3 lines by:

print(file.toxml())

#python #xml #programming 

Parsing and Modifying XML in Python
Gordon  Matlala

Gordon Matlala

1665964980

Templates for Rendering RSS Feeds For Your Jekyll Blog

Jekyll RSS Feed Templates

NOTE: If you're a fan of this project you should checkout the sister project: jekyll-json-feeds.

A few Liquid templates to use for rendering RSS feeds for your Jekyll blog. Featuring four kinds of feeds:

  • feed.xml — Renders the 10 most recent posts.
  • feed.category.xml — Only renders posts for a specific category. This example renders posts for a "miscellaneous" category.
  • feed.links.xml — Only contains posts that link to external websites noted by a link variable in the YAML Front Matter. Not a common Jekyll convention, but a good way to generating a linked list.
  • feed.articles.xml — Only showing articles that don't link to external sites; The opposite of feed.links.xml

How to use

  • Update _config.yml as noted below, or manually replace the variables.
  • Copy one of the xml (ie, feed.xml) files to the root directory of your Jekyll blog.
  • Run jekyll.

In your generated _site folder you should find a properly formatted feed at feed.xml.

Customizing _config.yml

These templates rely on a customized version of _config.yml. The following lines have been added:

name: Your Blog's Name
description: A description for your blog
url: http://your-blog-url.example.com
feed_items: 10
feed_update_period: daily
feed_update_frequency: 1

This makes it easy to reference the title, description and URL for your site in the feed templates using {{ site.name }}, {{ site.description }} and {{ site.url }}. Even if you're not using these feed templates, you might find these variables useful when you're designing your layouts.

The feed_* items shown above are the default. You can safely omit them.

Miscellany

Note on YAML Front Matter block: The xml files contain an empty YAML Front Matter block. This is necessary because Jekyll will not process a page with Liquid unless there is a YAML block at the top of the file.

Note on layouts: Previously, this block contained the line layout: none but that was found to cause a separate issue for some: https://github.com/snaptortoise/jekyll-rss-feeds/commit/209b83b504fde14722491ea5d9753189566c8598. However, if you've specified a default layout in your _config.yml file then you will most likely want to specify layout: none for your RSS feeds. Otherwise they will render in the default layout which is likely to be an HTML page. See this issue for reference: https://github.com/snaptortoise/jekyll-rss-feeds/issues/32

RSS Autodiscovery: If your template is not already setup to do so, make sure the RSS feeds are discoverable by browsers, bots, etc. by providing proper link tags to your Jekyll layout files (adapt href and title appropriately):

<link href="/blog/feed.xml" type="application/rss+xml" rel="alternate" title="Latest 10 blog posts (atom)" />

Refer to rssboard.org/rss-autodiscovery for details.

Validation: You can use the W3C Validator to make sure your feeds are formatted correctly: http://validator.w3.org/feed/

If you're a Pinboard user and found this repo useful, take a look at jekyll-pinboard. It allows you to load your Pinboard bookmarks into your Jekyll site with just a couple lines.

If you're looking for JSON feed templates to add to your Jekyll blog please checkout the sister project: jekyll-json-feeds.

 Download Details:

Author: Georgemandis
Source Code: https://github.com/georgemandis/jekyll-rss-feeds 
License: MIT license

#jekyll #xml #blog 

Templates for Rendering RSS Feeds For Your Jekyll Blog

A Small Library for Converting tokenized PHP Source Code into XML

Tokenizer

A small library for converting tokenized PHP source code into XML.

Installation

You can add this library as a local, per-project dependency to your project using Composer:

composer require theseer/tokenizer

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

composer require --dev theseer/tokenizer

Usage examples

$tokenizer = new TheSeer\Tokenizer\Tokenizer();
$tokens = $tokenizer->parse(file_get_contents(__DIR__ . '/src/XMLSerializer.php'));

$serializer = new TheSeer\Tokenizer\XMLSerializer();
$xml = $serializer->toXML($tokens);

echo $xml;

The generated XML structure looks something like this:

<?xml version="1.0"?>
<source xmlns="https://github.com/theseer/tokenizer">
 <line no="1">
  <token name="T_OPEN_TAG">&lt;?php </token>
  <token name="T_DECLARE">declare</token>
  <token name="T_OPEN_BRACKET">(</token>
  <token name="T_STRING">strict_types</token>
  <token name="T_WHITESPACE"> </token>
  <token name="T_EQUAL">=</token>
  <token name="T_WHITESPACE"> </token>
  <token name="T_LNUMBER">1</token>
  <token name="T_CLOSE_BRACKET">)</token>
  <token name="T_SEMICOLON">;</token>
 </line>
</source>

Download Details:

Author: Theseer
Source Code: https://github.com/theseer/tokenizer 
License: View license

#php #xml #tokenize 

A Small Library for Converting tokenized PHP Source Code into XML
Reid  Rohan

Reid Rohan

1665075840

XMLDOM: A PURE JS W3C Standard Based DOMParser & XMLSerializer

XMLDOM

A JavaScript implementation of W3C DOM for Node.js, Rhino and the browser. Fully compatible with W3C DOM level2; and some compatible with level3. Supports DOMParser and XMLSerializer interface such as in browser.

Install:

npm install xmldom

Example:

var DOMParser = require('xmldom').DOMParser;
var doc = new DOMParser().parseFromString(
    '<xml xmlns="a" xmlns:c="./lite">\n'+
        '\t<child>test</child>\n'+
        '\t<child></child>\n'+
        '\t<child/>\n'+
    '</xml>'
    ,'text/xml');
doc.documentElement.setAttribute('x','y');
doc.documentElement.setAttributeNS('./lite','c:x','y2');
var nsAttr = doc.documentElement.getAttributeNS('./lite','x')
console.info(nsAttr)
console.info(doc)

API Reference

DOMParser:

parseFromString(xmlsource,mimeType)
  • options extension by xmldom(not BOM standard!!)
//added the options argument
new DOMParser(options)

//errorHandler is supported
new DOMParser({
	/**
	 * locator is always need for error position info
	 */
	locator:{},
	/**
	 * you can override the errorHandler for xml parser
	 * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
	 */
	errorHandler:{warning:function(w){console.warn(w)},error:callback,fatalError:callback}
	//only callback model
	//errorHandler:function(level,msg){console.log(level,msg)}
})

XMLSerializer

serializeToString(node)

DOM level2 method and attribute:

Node

 attribute:
 	nodeValue|prefix
 readonly attribute:
 	nodeName|nodeType|parentNode|childNodes|firstChild|lastChild|previousSibling|nextSibling|attributes|ownerDocument|namespaceURI|localName
 method:	
 	insertBefore(newChild, refChild)
 	replaceChild(newChild, oldChild)
 	removeChild(oldChild)
 	appendChild(newChild)
 	hasChildNodes()
 	cloneNode(deep)
 	normalize()
 	isSupported(feature, version)
 	hasAttributes()

DOMImplementation

 method:
 	hasFeature(feature, version)
 	createDocumentType(qualifiedName, publicId, systemId)
 	createDocument(namespaceURI, qualifiedName, doctype)

Document : Node

 readonly attribute:
 	doctype|implementation|documentElement
 method:
 	createElement(tagName)
 	createDocumentFragment()
 	createTextNode(data)
 	createComment(data)
 	createCDATASection(data)
 	createProcessingInstruction(target, data)
 	createAttribute(name)
 	createEntityReference(name)
 	getElementsByTagName(tagname)
 	importNode(importedNode, deep)
 	createElementNS(namespaceURI, qualifiedName)
 	createAttributeNS(namespaceURI, qualifiedName)
 	getElementsByTagNameNS(namespaceURI, localName)
 	getElementById(elementId)

DocumentFragment : Node

Element : Node

 readonly attribute:
 	tagName
 method:
 	getAttribute(name)
 	setAttribute(name, value)
 	removeAttribute(name)
 	getAttributeNode(name)
 	setAttributeNode(newAttr)
 	removeAttributeNode(oldAttr)
 	getElementsByTagName(name)
 	getAttributeNS(namespaceURI, localName)
 	setAttributeNS(namespaceURI, qualifiedName, value)
 	removeAttributeNS(namespaceURI, localName)
 	getAttributeNodeNS(namespaceURI, localName)
 	setAttributeNodeNS(newAttr)
 	getElementsByTagNameNS(namespaceURI, localName)
 	hasAttribute(name)
 	hasAttributeNS(namespaceURI, localName)

Attr : Node

 attribute:
 	value
 readonly attribute:
 	name|specified|ownerElement

NodeList

 readonly attribute:
 	length
 method:
 	item(index)

NamedNodeMap

 readonly attribute:
 	length
 method:
 	getNamedItem(name)
 	setNamedItem(arg)
 	removeNamedItem(name)
 	item(index)
 	getNamedItemNS(namespaceURI, localName)
 	setNamedItemNS(arg)
 	removeNamedItemNS(namespaceURI, localName)

CharacterData : Node

 method:
 	substringData(offset, count)
 	appendData(arg)
 	insertData(offset, arg)
 	deleteData(offset, count)
 	replaceData(offset, count, arg)

Text : CharacterData

 method:
 	splitText(offset)

CDATASection

Comment : CharacterData

DocumentType

 readonly attribute:
 	name|entities|notations|publicId|systemId|internalSubset

Notation : Node

 readonly attribute:
 	publicId|systemId

Entity : Node

 readonly attribute:
 	publicId|systemId|notationName

EntityReference : Node

ProcessingInstruction : Node

 attribute:
 	data
 readonly attribute:
 	target

DOM level 3 support:

Node

 attribute:
 	textContent
 method:
 	isDefaultNamespace(namespaceURI){
 	lookupNamespaceURI(prefix)

DOM extension by xmldom

[Node] Source position extension;

 attribute:
 	//Numbered starting from '1'
 	lineNumber
 	//Numbered starting from '1'
 	columnNumber

Download Details:

Author: jindw
Source Code: https://github.com/jindw/xmldom 
License: View license

#javascript #xml #dom 

XMLDOM: A PURE JS W3C Standard Based DOMParser & XMLSerializer
Reid  Rohan

Reid Rohan

1665071640

Sax-js: A Sax Style Parser for JS

Sax js

A sax-style parser for XML and HTML.

Designed with node in mind, but should work fine in the browser or other CommonJS implementations.

What This Is

  • A very simple tool to parse through an XML string.
  • A stepping stone to a streaming HTML parser.
  • A handy way to deal with RSS and other mostly-ok-but-kinda-broken XML docs.

What This Is (probably) Not

  • An HTML Parser - That's a fine goal, but this isn't it. It's just XML.
  • A DOM Builder - You can use it to build an object model out of XML, but it doesn't do that out of the box.
  • XSLT - No DOM = no querying.
  • 100% Compliant with (some other SAX implementation) - Most SAX implementations are in Java and do a lot more than this does.
  • An XML Validator - It does a little validation when in strict mode, but not much.
  • A Schema-Aware XSD Thing - Schemas are an exercise in fetishistic masochism.
  • A DTD-aware Thing - Fetching DTDs is a much bigger job.

Regarding <!DOCTYPEs and <!ENTITYs

The parser will handle the basic XML entities in text nodes and attribute values: &amp; &lt; &gt; &apos; &quot;. It's possible to define additional entities in XML by putting them in the DTD. This parser doesn't do anything with that. If you want to listen to the ondoctype event, and then fetch the doctypes, and read the entities and add them to parser.ENTITIES, then be my guest.

Unknown entities will fail in strict mode, and in loose mode, will pass through unmolested.

Usage

var sax = require("./lib/sax"),
  strict = true, // set to false for html-mode
  parser = sax.parser(strict);

parser.onerror = function (e) {
  // an error happened.
};
parser.ontext = function (t) {
  // got some text.  t is the string of text.
};
parser.onopentag = function (node) {
  // opened a tag.  node has "name" and "attributes"
};
parser.onattribute = function (attr) {
  // an attribute.  attr has "name" and "value"
};
parser.onend = function () {
  // parser stream is done, and ready to have more stuff written to it.
};

parser.write('<xml>Hello, <who name="world">world</who>!</xml>').close();

// stream usage
// takes the same options as the parser
var saxStream = require("sax").createStream(strict, options)
saxStream.on("error", function (e) {
  // unhandled errors will throw, since this is a proper node
  // event emitter.
  console.error("error!", e)
  // clear the error
  this._parser.error = null
  this._parser.resume()
})
saxStream.on("opentag", function (node) {
  // same object as above
})
// pipe is supported, and it's readable/writable
// same chunks coming in also go out.
fs.createReadStream("file.xml")
  .pipe(saxStream)
  .pipe(fs.createWriteStream("file-copy.xml"))

Arguments

Pass the following arguments to the parser function. All are optional.

strict - Boolean. Whether or not to be a jerk. Default: false.

opt - Object bag of settings regarding string formatting. All default to false.

Settings supported:

  • trim - Boolean. Whether or not to trim text and comment nodes.
  • normalize - Boolean. If true, then turn any whitespace into a single space.
  • lowercase - Boolean. If true, then lowercase tag names and attribute names in loose mode, rather than uppercasing them.
  • xmlns - Boolean. If true, then namespaces are supported.
  • position - Boolean. If false, then don't track line/col/position.
  • strictEntities - Boolean. If true, only parse predefined XML entities (&amp;, &apos;, &gt;, &lt;, and &quot;)

Methods

write - Write bytes onto the stream. You don't have to do this all at once. You can keep writing as much as you want.

close - Close the stream. Once closed, no more data may be written until it is done processing the buffer, which is signaled by the end event.

resume - To gracefully handle errors, assign a listener to the error event. Then, when the error is taken care of, you can call resume to continue parsing. Otherwise, the parser will not continue while in an error state.

Members

At all times, the parser object will have the following members:

line, column, position - Indications of the position in the XML document where the parser currently is looking.

startTagPosition - Indicates the position where the current tag starts.

closed - Boolean indicating whether or not the parser can be written to. If it's true, then wait for the ready event to write again.

strict - Boolean indicating whether or not the parser is a jerk.

opt - Any options passed into the constructor.

tag - The current tag being dealt with.

And a bunch of other stuff that you probably shouldn't touch.

Events

All events emit with a single argument. To listen to an event, assign a function to on<eventname>. Functions get executed in the this-context of the parser object. The list of supported events are also in the exported EVENTS array.

When using the stream interface, assign handlers using the EventEmitter on function in the normal fashion.

error - Indication that something bad happened. The error will be hanging out on parser.error, and must be deleted before parsing can continue. By listening to this event, you can keep an eye on that kind of stuff. Note: this happens much more in strict mode. Argument: instance of Error.

text - Text node. Argument: string of text.

doctype - The <!DOCTYPE declaration. Argument: doctype string.

processinginstruction - Stuff like <?xml foo="blerg" ?>. Argument: object with name and body members. Attributes are not parsed, as processing instructions have implementation dependent semantics.

sgmldeclaration - Random SGML declarations. Stuff like <!ENTITY p> would trigger this kind of event. This is a weird thing to support, so it might go away at some point. SAX isn't intended to be used to parse SGML, after all.

opentagstart - Emitted immediately when the tag name is available, but before any attributes are encountered. Argument: object with a name field and an empty attributes set. Note that this is the same object that will later be emitted in the opentag event.

opentag - An opening tag. Argument: object with name and attributes. In non-strict mode, tag names are uppercased, unless the lowercase option is set. If the xmlns option is set, then it will contain namespace binding information on the ns member, and will have a local, prefix, and uri member.

closetag - A closing tag. In loose mode, tags are auto-closed if their parent closes. In strict mode, well-formedness is enforced. Note that self-closing tags will have closeTag emitted immediately after openTag. Argument: tag name.

attribute - An attribute node. Argument: object with name and value. In non-strict mode, attribute names are uppercased, unless the lowercase option is set. If the xmlns option is set, it will also contains namespace information.

comment - A comment node. Argument: the string of the comment.

opencdata - The opening tag of a <![CDATA[ block.

cdata - The text of a <![CDATA[ block. Since <![CDATA[ blocks can get quite large, this event may fire multiple times for a single block, if it is broken up into multiple write()s. Argument: the string of random character data.

closecdata - The closing tag (]]>) of a <![CDATA[ block.

opennamespace - If the xmlns option is set, then this event will signal the start of a new namespace binding.

closenamespace - If the xmlns option is set, then this event will signal the end of a namespace binding.

end - Indication that the closed stream has ended.

ready - Indication that the stream has reset, and is ready to be written to.

noscript - In non-strict mode, <script> tags trigger a "script" event, and their contents are not checked for special xml characters. If you pass noscript: true, then this behavior is suppressed.

Reporting Problems

It's best to write a failing test if you find an issue. I will always accept pull requests with failing tests if they demonstrate intended behavior, but it is very hard to figure out what issue you're describing without a test. Writing a test is also the best way for you yourself to figure out if you really understand the issue you think you have with sax-js.

Download Details:

Author: isaacs
Source Code: https://github.com/isaacs/sax-js 
License: View license

#javascript #node #xml #html 

Sax-js: A Sax Style Parser for JS

XML Layout for Flutter

xml_layout

XML layout for flutter. Layout your UI via xml at runtime. and support extending any customer widget. Here is a online preview.

Getting Started

write xml layout file like:

xml

<Text mainAxisAlignment="center">
    <for count="6">
        <Text>$item, You have pushed the button this many times:</Text>
    </for>
    <Text id="text-id">
        <attr:style>
            <TextStyle color="red"/>
        </attr:style>
        $counter
    </Text>
</Column>

dart

XMLLayout(
    temp: snapshot.data,
    objects: {
        "counter": _counter
    },
)

In this case

$counter for passing argument to the layout.

id attribute for selecting the widget or state.

XMLLayoutState state = ...;
// find the key of the Text 
GlobalKey key = state.find('text-id');

Registers

  • register
    • description: Register a constructor. It could convert a xml element to target object.
/**
 * Register a constructor
 * 
 * xml:
 * <MyClass width="10" height="10" />
 * 
 */
XMLLayout.register('MyClass', (node, key) {
    return MyClass(
        key: key,
        child: node.child<Widget>(),
        width: node.s<double>("width"),
        height: node.s<double>("height"),
    );
});
  • registerEnum
    • description: A shortcat to register a enum class. It could convert a attribute to the enum.
/**
 * Register a enum type
 * 
 * xml:
 * <Text textAlign="center">str</Text>
 */
XMLLayout.registerEnum(TextAlign.values);
  • registerInline(Type type, String name, bool field, InlineItemConstructor constructor)
    • description: Register a constructor which could convert a attribute to target type.
    • arguments:
      • field this constructor is for a static field or a constructor.
/**
 * <Text fontWeight="w200">str</Text>
 */
XmlLayout.registerInline(FontWeight, "w200", true, (node, method) {
  return FontWeight.w200;
});

/**
 * <Text textHeightBehavior="fromEncoded(20)">str</Text>
 */
XmlLayout.registerInline(TextHeightBehavior, "fromEncoded", false,
      (node, method) {
  return TextHeightBehavior.fromEncoded(int.tryParse(method[0]));
});

node.s<T>("name"), node.attribute<T>("name") convert subnode to target type

node.t<T>(), node.convert<T>() convert this node to target type

node.v<T>("value"), node.value<T>("value") convert text to target type

Widget Builder

<ListView.separated itemCount="$itemCount">
    <attr:itemBuilder>
        <Function returnType="Widget">
            <!-- get arguments of function via args -->
            <SetArgument return="index" argument="${args[1]}"/>
            <Call function="$getItem" return="itemData">
                <!-- pass argument to getItem function -->
                <Argument value="$index"/>
            </Call>
            <!-- The last element of Function tag would be the final result -->
            <Text>${itemData.title}</Text>
        </Function>
    </attr:itemBuilder>
</ListView.separated>

Script

<Function>
    <Script>
        set("index", ${args[1]})
        set("itemData", getItem($index))
    </Script>
    <!-- same as -->
    <SetArgument return="index" argument="${args[1]}"/>
    <Call function="$getItem" return="itemData">
        <Argument value="$index"/>
    </Call>
    <!-- end(same as) -->

    <Text>${itemData.title}</Text>
</Function>

Method

Method could be registerd via XmlLayout.registerInlineMethod, and can be used in a Xml attribute or Script tag.

Default methods:

  • isEmpty(a) => a.isEmpty()
  • isNotEmpty(a) => a.isNotEmpty()
  • equal(a, b, ...) => a == b ...
  • net(a, b) => a != b
  • mod(a, b) => a % b
  • div(a, b) => a / b
  • set(name, a) => env[name] = a
  • not(a) => !a
  • lt(a, b) => a < b
  • nlt(a, b) => a >= b
  • gt(a, b) => a > b
  • ngt(a, b) => a <= b
  • plus(a, b, ...) => a + b ...
  • minus(a, b, ...) => a - b ...
  • multiply(a, b, ...) => a * b ...
  • divide(a, b, ...) => a / b ...

Control Flow

A util to control the rendering logic. like:

<for count="$counter">
    <Text>$item, You have pushed the button this many times:</Text>
    <if candidate="equal(1, mod($item, 2))">
        <Text>Test text</Text>
    </if>
</for>
  • if tag is a if control flow.
    • attributes:
      • candidate a Boolean value, if true the children would be rendered, otherwise not be rendered.
  • else tag is a else control flow, could be placed after if or another else tag.
    • attributes:
      • candidate same as if tag.
  • for tag is a loop control flow.
    • attributes:
      • array a List value, iterates over array elements, each element for children one time.
      • count a Integer value, iterates children the value times. It is mutually exclusive with the array attribute.
      • item a String value, the name of each element, default is item.
      • index a String value, the name of the index of element, default is index.

Builder

You can write a script to generate the constructor code. In the example test.dart is the builder script.

Builder options:

  • entry_name
    • default: types
    • type: List<Type>
    • description: types in this list which will be processed.
  • collections_name
    • default: collections
    • type: List<Collection>
    • description: Collection type is used to process the collection class, such as: Colors and Icons.

ps: Colors and Icons is preprocessed just import it via:

import 'package:xml_layout/types/colors.dart' as colors;
import 'package:xml_layout/types/icons.dart' as icons;

// ...

colors.register();
icons.register();
  • coverts_name
    • default: converts
    • type: Map<String, String>
    • description: Every import uri will be test by the key value pair in this variable. if a import source uri is start with the key then it will be convert to the value.
  • imports_name
    • default: imports
    • type: List<String>
    • description: Extension import uris which will be write to the generated code.

Example

lib/test.dart

import 'package:flutter/material.dart';

const List<Type> types = [
  Text,
];

build.yaml

targets:
  $default:
    builders:
      xml_layout:
        generate_for:
          - lib/test.dart

Create the files above, then just run flutter pub run build_runner build. And you will get the generated code in lib/test.xml_layout.dart.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add xml_layout

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  xml_layout: ^2.3.15

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:xml_layout/xml_layout.dart'; 

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:xml_layout/xml_layout.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'test.xml_layout.dart' as xml_layout;
import 'package:xml_layout/types/colors.dart' as colors;
import 'package:xml_layout/types/icons.dart' as icons;
import 'package:xml_layout/types/function.dart';

void main() {
  colors.register();
  icons.register();
  xml_layout.register();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
        // This makes the visual density adapt to the platform that you run
        // the app on. For desktop platforms, the controls will be smaller and
        // closer together (more dense) than on mobile platforms.
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

Future<String> _loadLayout(String path) {
  return rootBundle.loadString(path);
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView(
          children: ListTile.divideTiles(tiles: [
        ListTile(
          title: Text("LayoutExample"),
          onTap: () => Navigator.of(context)
              .push(MaterialPageRoute(builder: (context) => _LayoutExample())),
        ),
        ListTile(
          title: Text("GridExample"),
          onTap: () => Navigator.of(context)
              .push(MaterialPageRoute(builder: (context) => _GridExample())),
        ),
        ListTile(
          title: Text("BuilderExample"),
          onTap: () => Navigator.of(context)
              .push(MaterialPageRoute(builder: (context) => _BuilderExample())),
        )
      ], context: context, color: Colors.black12)
              .toList()),
    );
  }
}

class _LayoutExample extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _LayoutExampleState();
}

class _LayoutExampleState extends State<_LayoutExample> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Layout Example"),
      ),
      body: Center(
        child: FutureBuilder<String>(
            future: _loadLayout("assets/layout.xml"),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return XmlLayout(
                  template: snapshot.data,
                  objects: {"counter": _counter},
                  onUnkownElement: (node, key) {
                    print("Unkown ${node.name ?? node.text}");
                  },
                );
              }
              return Container();
            }),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class _GridExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<String>(
        future: _loadLayout("assets/grid.xml"),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return XmlLayout(
              template: snapshot.data,
              objects: {
                "map": {
                  "pictures": [
                    "https://homepages.cae.wisc.edu/~ece533/images/baboon.png",
                    "https://homepages.cae.wisc.edu/~ece533/images/arctichare.png",
                    "https://homepages.cae.wisc.edu/~ece533/images/airplane.png"
                  ]
                },
                "print": (int idx) {
                  print("click ${idx}");
                }
              },
              onUnkownElement: (node, key) {
                print("Unkown ${node.name ?? node.text}");
              },
            );
          }
          return Container();
        });
  }
}

class _BuilderExample extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    List data = [{
      "title": "Title1",
      "subtitle": "Content1",
      "image": "https://homepages.cae.wisc.edu/~ece533/images/baboon.png"
    }, {
      "title": "Title2",
      "subtitle": "Content2",
      "image": "https://homepages.cae.wisc.edu/~ece533/images/arctichare.png"
    }, {
      "title": "Title3",
      "subtitle": "Content3",
      "image": "https://homepages.cae.wisc.edu/~ece533/images/airplane.png"
    }];
    return FutureBuilder<String>(
        future: _loadLayout("assets/list.xml"),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return XmlLayout(
              template: snapshot.data,
              objects: {
                "title": "BuilderExample",
                "itemCount": data.length,
                "getItem": (int idx) {
                  return data[idx];
                },
                "print": (int idx) {
                  print("click $idx");
                }
              },
              onUnkownElement: (node, key) {
                print("Unkown ${node.name ?? node.text}");
              },
            );
          }
          return Container();
        });
  }
} 

Download Details:

Author: gsioteam

Source Code: https://github.com/gsioteam/xml_layout

#xml #flutter 

XML Layout for Flutter

6 Favorite Golang Libraries and Tools for Manipulating XML

In today's post we will learn about 6 Favorite Golang Libraries and tools for Manipulating XML. 

What is XML?

The Extensible Markup Language (XML) is a simple text-based format for representing structured information: documents, data, configuration, books, transactions, invoices, and much more. It was derived from an older standard format called SGML (ISO 8879), in order to be more suitable for Web use.

Table of contents:

  • XML-Comp - Simple command line XML comparer that generates diffs of folders, files and tags.
  • XML2map - XML to MAP converter written Golang.
  • XMLwriter - Procedural XML generation API based on libxml2's xmlwriter module.
  • Xpath - XPath package for Go.
  • Xquery - XQuery lets you extract data from HTML/XML documents using XPath expression.
  • Zek - Generate a Go struct from XML.

1 - XML-Comp:

Simple command line XML comparer that generates diffs of folders, files and tags.

Installing

$ go get github.com/XML-Comp/XML-Comp

Running

$ XML-Comp -translation /path/to/language/translation

How this works?

You need the path that is called "translation", which are described bellow:

  • "translation": Full path directory of your RimWorld Language folder cloned from GitHub.

My "translation" path: /Users/arthur/Github/RimWorld-PortugueseBrazilian

With this path in hand, running xml-comp -translation your/path/to/translation will let you know in every file of your project what is missing by adding lines to it with what is needed to translate! That simple!

[RIMWORLD not installed in standard path]

If by any reason you did not install the game on Steam's standard path or want to use a different one, It's possible to use the original flag that exposes your customized path to the game as shows:

  • "original": Full path directory of your RimWorld English folder (optional). My "original" path (optional): /Users/arthur/Library/Application Support/Steam/steamapps/common/RimWorld/RimWorldMac.app/Mods/Core/Languages/English

In order to use this flag you'll need to parse it with the translation flag as in: xml-comp -original path/... -translation path/...

Comparing any kind of document

To compare any kind of files, all you need is to use the flag -doc <type name>, eg -doc html. This will use the paths that you gave only to compare the specified type of document. Another example:

$ XML-Comp -doc html -original path/to/It -translation path/to/It

OBS: This is not required, by default It's comparing all .xml files that are encountered.

Using only the comparer package

// Import the package
import "github.com/XML-Comp/XML-Comp/comparer"
// Set document type variable to the desired document
// without the "." | eg: "xml" or "html"
comparer.DocType = "html"
// Start the main function with the full paths to compare
// the firstPath is always what will be used as model
func main() {
    err := comparer.Compare(firstPath, comparingPath)
    if err != nil {
        log.Fatal(err)
    }
}

View on Github

2 - XML2map:

XML to MAP converter written Golang.

Getting started

1. install

go get -u github.com/sbabiv/xml2map

Or, using dep:

dep ensure -add github.com/sbabiv/xml2map

2. use it

func main() {
	data := `<container uid="FA6666D9-EC9F-4DA3-9C3D-4B2460A4E1F6" lifetime="2019-10-10T18:00:11">
				<cats>
					<cat>
						<id>CDA035B6-D453-4A17-B090-84295AE2DEC5</id>
						<name>moritz</name>
						<age>7</age> 	
						<items>
							<n>1293</n>
							<n>1255</n>
							<n>1257</n>
						</items>
					</cat>
					<cat>
						<id>1634C644-975F-4302-8336-1EF1366EC6A4</id>
						<name>oliver</name>
						<age>12</age>
					</cat>
					<dog color="gray">hello</dog>
				</cats>
				<color>white</color>
				<city>NY</city>
			</container>`

	decoder := xml2map.NewDecoder(strings.NewReader(data))
	result, err := decoder.Decode()

	if err != nil {
		fmt.Printf("%v\n", err)
	} else {
		fmt.Printf("%v\n", result)
	}
	
	v := result["container"].
		(map[string]interface{})["cats"].
			(map[string]interface{})["cat"].
				([]map[string]interface{})[0]["items"].
					(map[string]interface{})["n"].([]string)[1]
					
	fmt.Printf("n[1]: %v\n", v)
}

if you want to use your custom prefixes use the

NewDecoderWithPrefix(reader io.Reader, attrPrefix, textPrefix string) *Decoder

Go Playground

Output

map[container:map[@uid:FA6666D9-EC9F-4DA3-9C3D-4B2460A4E1F6 @lifetime:2019-10-10T18:00:11 cats:map[cat:[map[id:CDA035B6-D453-4A17-B090-84295AE2DEC5 name:moritz age:7 items:map[n:[1293 1255 1257]]] map[id:1634C644-975F-4302-8336-1EF1366EC6A4 name:oliver age:12]] dog:map[@color:gray #text:hello]] color:white city:NY]]

result: 1255

View on Github

3 - XMLwriter:

Procedural XML generation API based on libxml2's xmlwriter module.

Quick example:

func main() {
    b := &bytes.Buffer{}
    w := xmlwriter.Open(b)
    ec := &xmlwriter.ErrCollector{}
    defer ec.Panic()

    ec.Do(
        w.StartDoc(xmlwriter.Doc{})
        w.StartElem(xmlwriter.Elem{Name: "foo"})
        w.WriteAttr(xmlwriter.Attr{Name: "a1", Value: "val1"})
        w.WriteAttr(xmlwriter.Attr{Name: "a2", Value: "val2"})
        w.WriteComment(xmlwriter.Comment{"hello"})
        w.StartElem(xmlwriter.Elem{Name: "bar"})
        w.WriteAttr(xmlwriter.Attr{Name: "a1", Value: "val1"})
        w.WriteAttr(xmlwriter.Attr{Name: "a2", Value: "val2"})
        w.StartElem(xmlwriter.Elem{Name: "baz"})
        w.EndAllFlush()
    )
    fmt.Println(b.String())
}

xmlwriter is about twice as quick as using the stdlib's encoding/xml and offers total control of the output. If you don't require that level of control, it's probably better to stick with encoding/xml

BenchmarkWriterHuge-8     	     165	   7189290 ns/op	    4944 B/op	       4 allocs/op
BenchmarkWriterSmall-8    	  299679	      4035 ns/op	    4944 B/op	       4 allocs/op
BenchmarkGolangHuge-8      	      52	  21770422 ns/op	 4324496 B/op	   60008 allocs/op
BenchmarkGolangSmall-8    	  139767	      8828 ns/op	    5936 B/op	      28 allocs/op

xmlwriter is exhaustively tested using a fairly insane mess of C scripts you can find in the tester/ directory.

View on Github

4 - Xpath:

XPath package for Go.

Supported Features

The basic XPath patterns.

The basic XPath patterns cover 90% of the cases that most stylesheets will need.

node : Selects all child elements with nodeName of node.

* : Selects all child elements.

@attr : Selects the attribute attr.

@* : Selects all attributes.

node() : Matches an org.w3c.dom.Node.

text() : Matches a org.w3c.dom.Text node.

comment() : Matches a comment.

. : Selects the current node.

.. : Selects the parent of current node.

/ : Selects the document node.

a[expr] : Select only those nodes matching a which also satisfy the expression expr.

a[n] : Selects the nth matching node matching a When a filter's expression is a number, XPath selects based on position.

a/b : For each node matching a, add the nodes matching b to the result.

a//b : For each node matching a, add the descendant nodes matching b to the result.

//b : Returns elements in the entire document matching b.

a|b : All nodes matching a or b, union operation(not boolean or).

(a, b, c) : Evaluates each of its operands and concatenates the resulting sequences, in order, into a single result sequence

(a/b) : Selects all matches nodes as grouping set.

Node Axes

child::* : The child axis selects children of the current node.

descendant::* : The descendant axis selects descendants of the current node. It is equivalent to '//'.

descendant-or-self::* : Selects descendants including the current node.

attribute::* : Selects attributes of the current element. It is equivalent to @*

following-sibling::* : Selects nodes after the current node.

preceding-sibling::* : Selects nodes before the current node.

following::* : Selects the first matching node following in document order, excluding descendants.

preceding::* : Selects the first matching node preceding in document order, excluding ancestors.

parent::* : Selects the parent if it matches. The '..' pattern from the core is equivalent to 'parent::node()'.

ancestor::* : Selects matching ancestors.

ancestor-or-self::* : Selects ancestors including the current node.

self::* : Selects the current node. '.' is equivalent to 'self::node()'.

View on Github

5 - Xquery:

XQuery lets you extract data from HTML/XML documents using XPath expression.

Installation

go get github.com/antchfx/xquery

HTML Query 

Extract data from HTML document.

package main

import (
	"github.com/antchfx/xpath"
	"github.com/antchfx/xquery/html"
)

func main() {
	// Load HTML file.
	f, err := os.Open(`./examples/test.html`)
	if err != nil {
		panic(err)
	}
	// Parse HTML document.
	doc, err := htmlquery.Parse(f)
	if err != nil{
		panic(err)
	}

	// Option 1: using xpath's expr to matches nodes.
	expr := xpath.MustCompile("count(//div[@class='article'])")
	fmt.Printf("%f \n", expr.Evaluate(htmlquery.CreateXPathNavigator(doc)).(float64))

	expr = xpath.MustCompile("//a/@href")
	iter := expr.Evaluate(htmlquery.CreateXPathNavigator(doc)).(*xpath.NodeIterator)
	for iter.MoveNext() {
		fmt.Printf("%s \n", iter.Current().Value()) // output href
	}

	// Option 2: using build-in functions Find() to matches nodes.
	for _, n := range htmlquery.Find(doc, "//a/@href") {
		fmt.Printf("%s \n", htmlquery.SelectAttr(n, "href")) // output href
	}
}

XML Query 

Extract data from XML document.

package main

import (
	"github.com/antchfx/xpath"
	"github.com/antchfx/xquery/xml"
)

func main() {
	// Load XML document from file.
	f, err := os.Open(`./examples/test.xml`)
	if err != nil {
		panic(err)
	}
	// Parse XML document.
	doc, err := xmlquery.Parse(f)
	if err != nil{
		panic(err)
	}

	// Option 1: using xpath's expr to matches nodes.

	// sum all book's price via Evaluate()
	expr, err := xpath.Compile("sum(//book/price)")
	if err != nil {
		panic(err)
	}
	fmt.Printf("total price: %f\n", expr.Evaluate(xmlquery.CreateXPathNavigator(doc)).(float64))

	for _, n := range xmlquery.Find(doc, "//book") {
		fmt.Printf("%s : %s \n", n.SelectAttr("id"), xmlquery.FindOne(n, "title").InnerText())
	}
	
	// Option 2: using build-in functions FindOne() to matches node.
	n := xmlquery.FindOne(doc, "//book[@id='bk104']")
	fmt.Printf("%s \n", n.OutputXML(true))
}

View on Github

6 - Zek:

Generate a Go struct from XML.

Given some XML, run:

$ curl -s https://raw.githubusercontent.com/miku/zek/master/fixtures/e.xml | zek -e
// Rss was generated 2018-08-30 20:24:14 by tir on sol.
type Rss struct {
    XMLName xml.Name `xml:"rss"`
    Text    string   `xml:",chardata"`
    Rdf     string   `xml:"rdf,attr"`
    Dc      string   `xml:"dc,attr"`
    Geoscan string   `xml:"geoscan,attr"`
    Media   string   `xml:"media,attr"`
    Gml     string   `xml:"gml,attr"`
    Taxo    string   `xml:"taxo,attr"`
    Georss  string   `xml:"georss,attr"`
    Content string   `xml:"content,attr"`
    Geo     string   `xml:"geo,attr"`
    Version string   `xml:"version,attr"`
    Channel struct {
        Text          string `xml:",chardata"`
        Title         string `xml:"title"`         // ESS New Releases (Display...
        Link          string `xml:"link"`          // http://tinyurl.com/ESSNew...
        Description   string `xml:"description"`   // New releases from the Ear...
        LastBuildDate string `xml:"lastBuildDate"` // Mon, 27 Nov 2017 00:06:35...
        Item          []struct {
            Text        string `xml:",chardata"`
            Title       string `xml:"title"`       // Surficial geology, Aberde...
            Link        string `xml:"link"`        // https://geoscan.nrcan.gc....
            Description string `xml:"description"` // Geological Survey of Cana...
            Guid        struct {
                Text        string `xml:",chardata"` // 304279, 306212, 306175, 3...
                IsPermaLink string `xml:"isPermaLink,attr"`
            } `xml:"guid"`
            PubDate       string   `xml:"pubDate"`      // Fri, 24 Nov 2017 00:00:00...
            Polygon       []string `xml:"polygon"`      // 64.0000 -98.0000 64.0000 ...
            Download      string   `xml:"download"`     // https://geoscan.nrcan.gc....
            License       string   `xml:"license"`      // http://data.gc.ca/eng/ope...
            Author        string   `xml:"author"`       // Geological Survey of Cana...
            Source        string   `xml:"source"`       // Geological Survey of Cana...
            SndSeries     string   `xml:"SndSeries"`    // Bedford Institute of Ocea...
            Publisher     string   `xml:"publisher"`    // Natural Resources Canada,...
            Edition       string   `xml:"edition"`      // prelim., surficial data m...
            Meeting       string   `xml:"meeting"`      // Geological Association of...
            Documenttype  string   `xml:"documenttype"` // serial, open file, serial...
            Language      string   `xml:"language"`     // English, English, English...
            Maps          string   `xml:"maps"`         // 1 map, 5 maps, Publicatio...
            Mapinfo       string   `xml:"mapinfo"`      // surficial geology, surfic...
            Medium        string   `xml:"medium"`       // on-line; digital, digital...
            Province      string   `xml:"province"`     // Nunavut, Northwest Territ...
            Nts           string   `xml:"nts"`          // 066B, 095J; 095N; 095O; 0...
            Area          string   `xml:"area"`         // Aberdeen Lake, Mackenzie ...
            Subjects      string   `xml:"subjects"`
            Program       string   `xml:"program"`       // GEM2: Geo-mapping for Ene...
            Project       string   `xml:"project"`       // Rae Province Project Mana...
            Projectnumber string   `xml:"projectnumber"` // 340521, 343202, 340557, 3...
            Abstract      string   `xml:"abstract"`      // This new surficial geolog...
            Links         string   `xml:"links"`         // Online - En ligne (PDF, 9...
            Readme        string   `xml:"readme"`        // readme | https://geoscan....
            PPIid         string   `xml:"PPIid"`         // 34532, 35096, 35438, 2563...
        } `xml:"item"`
    } `xml:"channel"`
}

Install

$ go install github.com/miku/zek/cmd/zek@latest

View on Github

Thank you for following this article.

Related videos:

Parse XML Data In A Golang Application

#go #golang #xml 

6 Favorite Golang Libraries and Tools for Manipulating XML

Swift's 6 Popular XML Libraries

In this Swift article, let's learn about XML: Swift's 6 Popular XML Libraries

Table of contents:

  • AEXML - xml wrapper.
  • CheatyXML - A powerful framework designed to manage XML easily.
  • SwiftyXML - The most swifty way to deal with XML.
  • SWXMLHash - Simple XML parsing.
  • XMLCoder - XMLEncoder & XMLDecoder based on Codable protocols from the standard library.
  • XMLMapper - A simple way to map XML to Objects.

What is XML file in Swift?

If you are not familiar with XML, it's basically a precisely formatted text or string, which can be parsed into an array of objects containing the precious information. A good tutorial about XML can be found here.


Swift's 6 Popular XML Libraries

  1. AEXML

Swift minion for simple and lightweight XML parsing

Intro

This is not a robust full featured XML parser, but rather simple, lightweight and easy to use utility for casual XML handling.

Features

  • Read XML data
  • Write XML string
  • Covered with unit tests
  • Covered with inline docs

Usage

Read XML

Let's say this is some XML string you picked up somewhere and made a variable data: Data from that.

<?xml version="1.0" encoding="utf-8"?>
<animals>
    <cats>
        <cat breed="Siberian" color="lightgray">Tinna</cat>
        <cat breed="Domestic" color="darkgray">Rose</cat>
        <cat breed="Domestic" color="yellow">Caesar</cat>
        <cat></cat>
    </cats>
    <dogs>
        <dog breed="Bull Terrier" color="white">Villy</dog>
        <dog breed="Bull Terrier" color="white">Spot</dog>
        <dog breed="Golden Retriever" color="yellow">Betty</dog>
        <dog breed="Miniature Schnauzer" color="black">Kika</dog>
    </dogs>
</animals>

This is how you can use AEXML for working with this data:
(for even more examples, look at the unit tests code included in project)

guard let
    let xmlPath = Bundle.main.path(forResource: "example", ofType: "xml"),
    let data = try? Data(contentsOf: URL(fileURLWithPath: xmlPath))
else { return }

do {
    let xmlDoc = try AEXMLDocument(xml: data, options: options)
        
    // prints the same XML structure as original
    print(xmlDoc.xml)
    
    // prints cats, dogs
    for child in xmlDoc.root.children {
        print(child.name)
    }
    
    // prints Optional("Tinna") (first element)
    print(xmlDoc.root["cats"]["cat"].value)
    
    // prints Tinna (first element)
    print(xmlDoc.root["cats"]["cat"].string)
    
    // prints Optional("Kika") (last element)
    print(xmlDoc.root["dogs"]["dog"].last?.value)
    
    // prints Betty (3rd element)
    print(xmlDoc.root["dogs"].children[2].string)
    
    // prints Tinna, Rose, Caesar
    if let cats = xmlDoc.root["cats"]["cat"].all {
        for cat in cats {
            if let name = cat.value {
                print(name)
            }
        }
    }
    
    // prints Villy, Spot
    for dog in xmlDoc.root["dogs"]["dog"].all! {
        if let color = dog.attributes["color"] {
            if color == "white" {
                print(dog.string)
            }
        }
    }
    
    // prints Tinna
    if let cats = xmlDoc.root["cats"]["cat"].all(withValue: "Tinna") {
        for cat in cats {
            print(cat.string)
        }
    }
    
    // prints Caesar
    if let cats = xmlDoc.root["cats"]["cat"].all(withAttributes: ["breed" : "Domestic", "color" : "yellow"]) {
        for cat in cats {
            print(cat.string)
        }
    }
    
    // prints 4
    print(xmlDoc.root["cats"]["cat"].count)
    
    // prints Siberian
    print(xmlDoc.root["cats"]["cat"].attributes["breed"]!)
    
    // prints <cat breed="Siberian" color="lightgray">Tinna</cat>
    print(xmlDoc.root["cats"]["cat"].xmlCompact)
    
    // prints Optional(AEXML.AEXMLError.elementNotFound)
    print(xmlDoc["NotExistingElement"].error)
}
catch {
    print("\(error)")
}

View on GitHub


2.  CheatyXML

CheatyXML is a Swift framework designed to manage XML easily.

Requirements

  • iOS 8.0 or later
  • tvOS 9.0 or later

Installation

Cocoapods

If you're using cocoapods, just add pod 'CheatyXML' into your Podfile file.

Manual

To install this, simply add the .xcodeproj to your project, and do not forget to link the .framework.

Whenever you want to use it in your code, simply type:

import CheatyXML

Usage

Let's take the following XML content for all of our examples:

<blog version="1.0" creator="lobodart">
    <name>MyAwesomeBlog!</name>
    <users>
        <admin is_active="true">lobodart</admin>
        <moderator is_active="false">slash705</moderator>
        <moderator is_active="...">...</moderator>
        ...
    </users>
    <article>
        <title>My first article</title>
        <description>This is the first article</description>
        <infos>
            <date>2015-03-15 15:42:42</date>
            <rate>42</rate>
        </infos>
        ...
    </article>
    <article>
        ...
    </article>
    ...
</blog>

View on GitHub


3.  SwiftyXML

SwiftyXML use most swifty way to deal with XML data.

Features

  •  Infinity subscript
  •  dynamicMemberLookup Support (use $ started string to subscript attribute)
  •  Optional | Non-optional value access
  •  Directly access Enum type value (enums extends from RawRepresentable)
  •  Directly for loop in XML children nodes
  •  Accurate error throwing
  •  XML construct, formatting
  •  Single source file

Sample XML:

<catalog>
	<product description="Cardigan Sweater" product_image="cardigan.jpg" >
		<catalog_item gender="Men's" >
			<item_number>QWZ5671</item_number>
			<price>39.95</price>
			<size description="Medium" >
				<color_swatch image="red_cardigan.jpg" >Red</color_swatch>
				<color_swatch image="burgundy_cardigan.jpg" >Burgundy</color_swatch>
			</size>
			<size description="Large" >
				<color_swatch image="red_cardigan.jpg" >Red</color_swatch>
				<color_swatch image="burgundy_cardigan.jpg" >Burgundy</color_swatch>
			</size>
		</catalog_item>
		<catalog_item gender="Women's" >
			<item_number>RRX9856</item_number>
			<price>42.50</price>
			<size description="Small" >
				<color_swatch image="red_cardigan.jpg" >Red</color_swatch>
				<color_swatch image="navy_cardigan.jpg" >Navy</color_swatch>
				<color_swatch image="burgundy_cardigan.jpg" >Burgundy</color_swatch>
			</size>
		</catalog_item>
	</product>
</catalog>

With SwiftyXML all you have to do is:

let xml = XML(string: xmlContent)
let color0 = xml.product.catalog_item.size.color_swatch.1.string //"Burgundy"
// notice that, we use "$" prefix for subscript attribute
let description0 = xml.product.catalog_item.size.1.$description.string //"Large"

This is same as below, SwiftyXML will auto pick the first element as default:

let xml = XML(data: xmlFileData)
let color = xml.product.0.catalog_item.0.size.0.color_swatch.1.string //return "Burgundy"

What about if you input some wrong keys:

let xml = XML(data: xmlFileData)
// print the error
if let color1 = xml.product.catalog_item.wrong_size.wrong_color.1.xml {
    // do stuff ~
    print(color1)
} else {
    print(xml.product.catalog_item.wrong_size.wrong_color.1.error) //.product.0.catalog_item.0: no such children named: "wrong_size"
}

View on GitHub


4.  SWXMLHash

SWXMLHash is a relatively simple way to parse XML in Swift. If you're familiar with NSXMLParser, this library is a simple wrapper around it. Conceptually, it provides a translation from XML to a dictionary of arrays (aka hash).

Requirements

  • iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 8.0+

Installation

SWXMLHash can be installed using CocoaPods, Carthage, Swift Package Manager, or manually.

CocoaPods

To install CocoaPods, run:

$ gem install cocoapods

Then create a Podfile with the following contents:

platform :ios, '10.0'
use_frameworks!

target 'YOUR_TARGET_NAME' do
  pod 'SWXMLHash', '~> 7.0.0'
end

Finally, run the following command to install it:

$ pod install

Carthage

To install Carthage, run (using Homebrew):

$ brew update
$ brew install carthage

Then add the following line to your Cartfile:

github "drmohundro/SWXMLHash" ~> 7.0

View on GitHub


5.  XMLCoder

Encoder & Decoder for XML using Swift's Codable protocols.

This package is a fork of the original ShawnMoore/XMLParsing with more features and improved test coverage. Automatically generated documentation is available on our GitHub Pages.

Example

import XMLCoder
import Foundation

let sourceXML = """
<note>
    <to>Bob</to>
    <from>Jane</from>
    <heading>Reminder</heading>
    <body>Don't forget to use XMLCoder!</body>
</note>
"""

struct Note: Codable {
    let to: String
    let from: String
    let heading: String
    let body: String
}

let note = try! XMLDecoder().decode(Note.self, from: Data(sourceXML.utf8))

let encodedXML = try! XMLEncoder().encode(note, withRootKey: "note")

Advanced features

The following features are available in 0.4.0 release or later (unless stated otherwise):

Stripping namespace prefix

Sometimes you need to handle an XML namespace prefix, like in the XML below:

<h:table xmlns:h="http://www.w3.org/TR/html4/">
  <h:tr>
    <h:td>Apples</h:td>
    <h:td>Bananas</h:td>
  </h:tr>
</h:table>

Stripping the prefix from element names is enabled with shouldProcessNamespaces property:

struct Table: Codable, Equatable {
    struct TR: Codable, Equatable {
        let td: [String]
    }

    let tr: [TR]
}


let decoder = XMLDecoder()

// Setting this property to `true` for the namespace prefix to be stripped
// during decoding so that key names could match.
decoder.shouldProcessNamespaces = true

let decoded = try decoder.decode(Table.self, from: xmlData)

View on GitHub


6.  XMLMapper

XMLMapper is a framework written in Swift that makes it easy for you to convert your model objects (classes and structs) to and from XML.

How to use

To support mapping, a class or struct just needs to implement the XMLMappable protocol:

var nodeName: String! { get set }
init?(map: XMLMap)
mutating func mapping(map: XMLMap)

XMLMapper uses the <- operator to define how each property maps to and from XML:

<food>
  <name>Belgian Waffles</name>
  <price>5.95</price>
  <description>
    Two of our famous Belgian Waffles with plenty of real maple syrup
  </description>
  <calories>650</calories>
</food>
class Food: XMLMappable {
    var nodeName: String!

    var name: String!
    var price: Float!
    var description: String?
    var calories: Int?

    required init?(map: XMLMap) {}

    func mapping(map: XMLMap) {
        name <- map["name"]
        price <- map["price"]
        description <- map["description"]
        calories <- map["calories"]
    }
}

XMLMapper can map classes or structs composed of the following types:

  • Int
  • Bool
  • Double
  • Float
  • String
  • RawRepresentable (Enums)
  • Array<Any>
  • Dictionary<String, Any>
  • Object<T: XMLBaseMappable>
  • Array<T: XMLBaseMappable>
  • Set<T: XMLBaseMappable>
  • Dictionary<String, T: XMLBaseMappable>
  • Dictionary<String, Array<T: XMLBaseMappable>>
  • Optionals and Implicitly Unwrapped Optionals of all the above

View on GitHub


XML Swift FAQ

  • What is XML iOS?

Like Android XML, iOS also used XML file for Designing the UI part call Storyboard or nib file. if you could Right-Click and select Open As "Source code" you will find XML code their. The way android used Layout for UI is different from iOS. iOS used Auto-layout technology to set Margin and layout.

  • What is XML data parsing?

Definition. XML parsing is the process of reading an XML document and providing an interface to the user application for accessing the document. An XML parser is a software apparatus that accomplishes such tasks.

  • What is Swift XML?

A markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. Swift and XML can be categorized as "Languages" tools. Swift is an open source tool with 48.4K GitHub stars and 7.76K GitHub forks.

  • What is XML formatting?

What is XML? The Extensible Markup Language (XML) is a simple text-based format for representing structured information: documents, data, configuration, books, transactions, invoices, and much more. It was derived from an older standard format called SGML (ISO 8879), in order to be more suitable for Web use.


Related videos:

Parse XML in iOS with Swift - Build a RSS News Reader App


Related posts:

#xml #swift 

Swift's 6 Popular XML Libraries
Reid  Rohan

Reid Rohan

1662960185

5 Method Essential HTML/XML Parsing with JavaScript

In today's post we will learn about 5 Method Essential HTML/XML Parsing with JavaScript.

What is XML parsing in JavaScript?

Many browsers have an in-built XML parser that can transform the document of XML into human-readable formats, we can also say that the XML parser is a software package that can interact with an XML document to check the format of the document and to validate it through the client applications because to manipulate data which is comes from the XML file is quite hard. The XML parser works between the client application and the XML document and the work of it is to validate the document which passing through it and it is mainly designed to the document of XML and it has programs to read the XML document. The XML parsing is working with all browsers to read and write it and it has a simple API. As it has a DOM parser and the SAX parser which can help to parse the text, parse the string, and also parse the file.

A long time ago the XML parser has been added to the browsers and the JavaScript need to add a new parser for other languages so that for the other languages it has to define the data structure which allows serialization of the data.

Table of contents:

  • Htmlparser2 - forgiving html and xml parser.
  • Sax-js - A sax style parser for JS.
  • Cheerio - Fast, flexible, and lean implementation of core jQuery designed specifically for the server. 
  • js-xss - Sanitize untrusted HTML (to prevent XSS) with a configuration specified by a Whitelist.
  • surgeon - Declarative DOM extraction expression evaluator

1 - Htmlparser2: Forgiving html and xml parser.

Installation

npm install htmlparser2

Usage

htmlparser2 itself provides a callback interface that allows consumption of documents with minimal allocations. For a more ergonomic experience, read Getting a DOM below.

import * as htmlparser2 from "htmlparser2";

const parser = new htmlparser2.Parser({
    onopentag(name, attributes) {
        /*
         * This fires when a new tag is opened.
         *
         * If you don't need an aggregated `attributes` object,
         * have a look at the `onopentagname` and `onattribute` events.
         */
        if (name === "script" && attributes.type === "text/javascript") {
            console.log("JS! Hooray!");
        }
    },
    ontext(text) {
        /*
         * Fires whenever a section of text was processed.
         *
         * Note that this can fire at any point within text and you might
         * have to stitch together multiple pieces.
         */
        console.log("-->", text);
    },
    onclosetag(tagname) {
        /*
         * Fires when a tag is closed.
         *
         * You can rely on this event only firing when you have received an
         * equivalent opening tag before. Closing tags without corresponding
         * opening tags will be ignored.
         */
        if (tagname === "script") {
            console.log("That's it?!");
        }
    },
});
parser.write(
    "Xyz <script type='text/javascript'>const foo = '<<bar>>';</script>"
);
parser.end();

Output (with multiple text events combined):

--> Xyz
JS! Hooray!
--> const foo = '<<bar>>';
That's it?!

View on Github

2 - Sax-js: A sax style parser for JS.

What This Is

  • A very simple tool to parse through an XML string.
  • A stepping stone to a streaming HTML parser.
  • A handy way to deal with RSS and other mostly-ok-but-kinda-broken XML docs.

What This Is (probably) Not

  • An HTML Parser - That's a fine goal, but this isn't it. It's just XML.
  • A DOM Builder - You can use it to build an object model out of XML, but it doesn't do that out of the box.
  • XSLT - No DOM = no querying.
  • 100% Compliant with (some other SAX implementation) - Most SAX implementations are in Java and do a lot more than this does.
  • An XML Validator - It does a little validation when in strict mode, but not much.
  • A Schema-Aware XSD Thing - Schemas are an exercise in fetishistic masochism.
  • A DTD-aware Thing - Fetching DTDs is a much bigger job.

Usage

var sax = require("./lib/sax"),
  strict = true, // set to false for html-mode
  parser = sax.parser(strict);

parser.onerror = function (e) {
  // an error happened.
};
parser.ontext = function (t) {
  // got some text.  t is the string of text.
};
parser.onopentag = function (node) {
  // opened a tag.  node has "name" and "attributes"
};
parser.onattribute = function (attr) {
  // an attribute.  attr has "name" and "value"
};
parser.onend = function () {
  // parser stream is done, and ready to have more stuff written to it.
};

parser.write('<xml>Hello, <who name="world">world</who>!</xml>').close();

// stream usage
// takes the same options as the parser
var saxStream = require("sax").createStream(strict, options)
saxStream.on("error", function (e) {
  // unhandled errors will throw, since this is a proper node
  // event emitter.
  console.error("error!", e)
  // clear the error
  this._parser.error = null
  this._parser.resume()
})
saxStream.on("opentag", function (node) {
  // same object as above
})
// pipe is supported, and it's readable/writable
// same chunks coming in also go out.
fs.createReadStream("file.xml")
  .pipe(saxStream)
  .pipe(fs.createWriteStream("file-copy.xml"))

View on Github

3 - Cheerio: Fast, flexible, and lean implementation of core jQuery designed specifically for the server. 

Installation

npm install cheerio

API

Markup example we'll be using:

<ul id="fruits">
  <li class="apple">Apple</li>
  <li class="orange">Orange</li>
  <li class="pear">Pear</li>
</ul>

This is the HTML markup we will be using in all of the API examples.

Loading

First you need to load in the HTML. This step in jQuery is implicit, since jQuery operates on the one, baked-in DOM. With Cheerio, we need to pass in the HTML document.

This is the preferred method:

// ES6 or TypeScript:
import * as cheerio from 'cheerio';

// In other environments:
const cheerio = require('cheerio');

const $ = cheerio.load('<ul id="fruits">...</ul>');

$.html();
//=> <html><head></head><body><ul id="fruits">...</ul></body></html>

View on Github

4 - js-xss: Sanitize untrusted HTML (to prevent XSS) with a configuration specified by a Whitelist.

Install

NPM

npm install xss

Bower

bower install xss

Or

bower install https://github.com/leizongmin/js-xss.git

Usages

On Node.js

var xss = require("xss");
var html = xss('<script>alert("xss");</script>');
console.log(html);

On Browser

Shim mode (reference file test/test.html):

<script src="https://rawgit.com/leizongmin/js-xss/master/dist/xss.js"></script>
<script>
  // apply function filterXSS in the same way
  var html = filterXSS('<script>alert("xss");</scr' + "ipt>");
  alert(html);
</script>

AMD mode - shim:

<script>
  require.config({
    baseUrl: "./",
    paths: {
      xss: "https://rawgit.com/leizongmin/js-xss/master/dist/xss.js",
    },
    shim: {
      xss: { exports: "filterXSS" },
    },
  });
  require(["xss"], function (xss) {
    var html = xss('<script>alert("xss");</scr' + "ipt>");
    alert(html);
  });
</script>

View on Github

5 - Surgeon: Declarative DOM extraction expression evaluator

Powerful, succinct, composable, extendable, declarative API.

articles:
- select article {0,}
- body:
  - select .body
  - read property innerHTML
  imageUrl:
  - select img
  - read attribute src
  summary:
  - select ".body p:first-child"
  - read property innerHTML
  - format text
  title:
  - select .title
  - read property textContent
pageName:
- select .body
- read property innerHTML

Not succinct enough for you? Use aliases and the pipe operator (|) to shorten and concatenate the commands:

articles:
- sm article
- body: s .body | rp innerHTML
  imageUrl: s img | ra src
  summary: s .body p:first-child | rp innerHTML | f text
  title: s .title | rp textContent
pageName: s .body | rp innerHTML

Have you got suggestions for improvement? I am all ears.

View on Github

Thank you for following this article.

Related videos:

What is the DOMParser? - JavaScript Tutorial

 

#javascript #html #xml 

5 Method Essential HTML/XML Parsing with JavaScript

An XPath Selector for Locating Html and Xml Elements

xpath_selector

An XPath selector for locating Html and Xml elements

English | 简体中文

Parser

This library is for xpath selection only, you must define a parser, and here is my prebuilt parser:

xpath_selector_html_parser by html

xpath_selector_xml_parser by xml

If you want to use another parser, refer to these two libraries to define your own parser that implements the XPathNode<T> interface

Extended syntax

In the attribute selector, the parser extends the following attribute selector in CSS style

ExpressionCssDescription
[@attr='value'][attr="value"]Selects all elements with attr="value"
[@attr~='value'][attr~="value"]Selects all elements attribute containing the word "value"
[@attr^='value'][attr^="value"]Selects all elements whose attr attribute value begins with "value"
[@attr$='value'][attr$="value"]Selects all elements whose attr attribute value ends with "value"
[@attr*='value'][attr*="value"]Selects all elements whose attr attribute value contains the substring "value"

Breaking changes

1.x => 2.0

  1. Remove classXPathElement, which merge toXPathNode
  2. In XPathResult, elements=>nodes, elements=>element

2.0 => 3.0

  1. Remove the built-in html and xlm parsers, and make it independent to xpath_selector_html_parser and xpath_selector_xml_parser

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add xpath_selector

With Flutter:

 $ flutter pub add xpath_selector

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  xpath_selector: ^3.0.1

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:xpath_selector/xpath_selector.dart'; 

Download Details:

Author: simonkimi

Source Code: https://github.com/simonkimi/xpath_selector

#html #xml #android 

An XPath Selector for Locating Html and Xml Elements

XmltoDict.jl: Julia Module That Makes Working with XML

xmltodict.jl

Julia module that makes working with XML feel like you are working with JSON (inspired by the Python module xmltodict).

Usage


xmltest = """
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book category="COOKING" tag="first">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
  </book>
  <book category="CHILDREN">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
  </book>
  <newspaper category="news">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
  </newspaper>
</bookstore>
"""

xdict = xmlparse_string(xmltest)
xt1["bookstore"]["book"][1] 

Results in:

OrderedDict{String,Any} with 6 entries: "@category" => "COOKING" "@tag" => "first" "title" => ["@lang"=>"en","#text"=>"Everyday Italian"] "author" => ["#text"=>"Giada De Laurentiis"] "year" => ["#text"=>"2005"] "price" => ["#text"=>"30.00"]

Macro Extensions

xt1["bookstore"][x2d"book"] 
xt1["bookstore"][x2d"newspaper"] => {"@category" => "news", "title" => { ... }, ... }
xt1["bookstore"][x2d"newspaper+"] => [ {"@category" => "news", "title" => { ... }, ... }, ]
xt1["bookstore"][x2d"magazine"] => key error
xt1["bookstore"][x2d"newspaper*"] => [ ] 

Download Details:

Author: Elcritch
Source Code: https://github.com/elcritch/XmlToDict.jl 
License: MIT, Unknown licenses found

#julia #xml #json 

XmltoDict.jl: Julia Module That Makes Working with XML