Set xml attribute java

JDOM Element Example, How to set attribute of xml element in java.

In this tutorial, you will see how to set attribute of xml element in java.

In this tutorial, you will see how to set attribute of xml element in java.

JDOM Element Example, How to set attribute of xml element in java.

In this tutorial, we will see how to set attribute of xml element in java with the help of
JDOM library. JDOM is used for parsing, creating, manipulating, and serializing XML
documents.

In this example, we will use some methods. DOMBuilder is a class that build a
JDOMDocument of xml file. The getRootElement method of Document class is
used for accessing root element. The setAttribute(String name, String value)
method set a attribute of an element with given name and value. The Element class
is available in org.jdom.Element pacakage.

Element API.

Return Type Method Description
Element setAttribute(String name, String value) The setAttribute(. ) method set attribute of element.

Code:

CloneAttribute.java

package roseindia;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.DOMBuilder;
import java.io.File;

public class SetAttribute <
public static void main ( String [] args ) <
try <
String data = «student.xml» ;
File file = new File ( data ) ;
DOMBuilder builder = new DOMBuilder ( false ) ;
Document doc = builder.build ( file ) ;
Element root = doc.getRootElement () ;
System.out.println ( «Root Element» + root ) ;
Element att = root.setAttribute ( «id» , «001» ) ;
Attribute attribute = att.getAttribute ( «id» ) ;
System.out.println ( «Atttribute : » + attribute ) ;
> catch ( Exception e ) <
System.out.println ( «Execption » + e.getMessage ()) ;
>
>
>

Output:

Источник

Java Tutorial/XML/Attribute

import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; public class Main

public static void main(String[] argv) throws Exception < DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder loader = factory.newDocumentBuilder(); Document document = loader.parse("sample.xml"); Element purchaseOrder = document.getDocumentElement(); Attr orderDate = purchaseOrder.getAttributeNode("date"); System.out.println(orderDate.getValue()); NamedNodeMap attrs = purchaseOrder.getAttributes(); int attrsCount = attrs.getLength(); for (int i = 0; i < attrsCount; i++) < Attr item = (Attr) attrs.item(i); System.out.println(""" + item.getName() + "" = "" + item.getValue() + """); >>

Adding and Removing an Attribute in a DOM Element

import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; public class Main

public static void main(String[] argv) throws Exception < DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); factory.setExpandEntityReferences(false); Document doc = factory.newDocumentBuilder().parse(new File("filename")); Element element = doc.getElementById("key1"); element.setAttribute("newAttrName", "attrValue"); element.setAttribute("newAttrName", "<>&\"""); element.removeAttribute("value"); boolean has = element.hasAttribute("value"); // true String attrValue = element.getAttribute("value"); // mydefault >

Determining If an Attribute Was Supplied in a DOM Element

import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; public class Main
public static void main(String[] argv) throws Exception

Extracting attribute values from XML elements

import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class Main
public static void main(String[] argv) throws Exception

> class SaxHandler extends DefaultHandler

public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException < if (qName.equals("order")) < String date = attrs.getValue("date"); String number = attrs.getValue("number"); System.out.println("Order #" + number + " date is "" + date + """); >>

Getting and Setting an Attribute in a DOM Element

import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; public class Main

public static void main(String[] argv) throws Exception < DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); factory.setExpandEntityReferences(false); Document doc = factory.newDocumentBuilder().parse(new File("filename")); Element element = doc.getElementById("key1"); boolean has = element.hasAttribute("value"); String attrValue = element.getAttribute("value"); element.setAttribute("value", "newValue1"); element = doc.getElementById("key2"); has = element.hasAttribute("value"); attrValue = element.getAttribute("value"); element.setAttribute("value", "az"); >

Listing All the Attributes of a DOM Element

import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; public class Main

public static void main(String[] argv) throws Exception < DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); factory.setExpandEntityReferences(false); Document doc = factory.newDocumentBuilder().parse(new File("filename")); Element element = doc.getElementById("key1"); NamedNodeMap attrs = element.getAttributes(); int numAttrs = attrs.getLength(); for (int i = 0; i < numAttrs; i++) < Attr attr = (Attr) attrs.item(i); String attrName = attr.getNodeName(); String attrValue = attr.getNodeValue(); >>

Remove all attributes by first making a copy of the attribute names and then using the list to remove the attributes:

import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; public class Main

public static void main(String[] argv) throws Exception < DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); factory.setExpandEntityReferences(false); Document doc = factory.newDocumentBuilder().parse(new File("filename")); Element element = doc.getElementById("key1"); NamedNodeMap attrs = element.getAttributes(); String[] names = new String[attrs.getLength()]; for (int i = 0; i < names.length; i++) < names[i] = attrs.item(i).getNodeName(); >for (int i = 0; i < names.length; i++) < attrs.removeNamedItem(names[i]); >>

Removing All the Attributes in a DOM Element

import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; public class Main

public static void main(String[] argv) throws Exception < DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); factory.setExpandEntityReferences(false); Document doc = factory.newDocumentBuilder().parse(new File("filename")); Element element = doc.getElementById("key1"); NamedNodeMap attrs = element.getAttributes(); while (attrs.getLength() >0) < attrs.removeNamedItem(attrs.item(0).getNodeName()); >>

Источник

How to add attributes in XML elements using JAXB in dynamic web application for Java EE

If you are trying to add an XML attribute in an XML entry using JAXB this information is for you. First of all you need to understand what an attribute in a XML entry means: in strict sense an attribute provides additional information about an element, this information could be useful to add metadata, states of an XML entry or any other extra information you want. As you know, all attribute’s values must always be quoted. Either single or double quotes can be used. Now, what’s better: use many attributes o XML elements? well, the answer according to W3C is: avoid attributes and try to adapt them to XML elements; but in my case I needed to use attributes.

java

1) Imagine you need to get this kind of XML output:

  profileID1 alex_arriaga Big Dealer Supply Co TOOL_ZH  profileID2 alex_arriaga_m TOOL_SX  

2) And you are using JAXB for dynamic generating for your XML document:

DataUserProfiles is a composed class to hold all profile data.

package com.base22.model; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="profiles") @XmlAccessorType(XmlAccessType.FIELD) public class DataUserProfiles < @XmlElement(name="profiles") private UserProfilesList profilesList; public DataUserProfiles()< >public DataUserProfiles(UserProfilesList profilesList) < this.profilesList = profilesList; >public UserProfilesList getProfilesList() < return profilesList; >public void setProfilesList(UserProfilesList profilesList) < this.profilesList = profilesList; >>

This class UserProfileList contains the definition of an attribute called current.

package com.base22.model; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * This class was created to hold an attribute "current" on the list of User's profiles * It could be removed if another library can be added (like EclipseLink MOXy to support XmlPath annotation) * @author Alex Arriaga (base22.com) * */ @XmlRootElement(name="profiles") @XmlAccessorType(XmlAccessType.FIELD) public class UserProfilesList < @XmlElement(name="profile") private Listprofiles; @XmlAttribute(name="current") private String currentUserProfile; public UserProfilesList()< this.profiles = new ArrayList(); > public UserProfilesList(List listProfiles) < this.profiles = listProfiles; >public UserProfilesList(List listProfiles, String currentUserProfile) < this.profiles = listProfiles; this.currentUserProfile = currentUserProfile; >public List getProfiles() < return profiles; >public void setProfiles(List profiles) < this.profiles = profiles; >public String getCurrentUserProfile() < return currentUserProfile; >public void setCurrentUserProfile(String currentUserProfile) < this.currentUserProfile = currentUserProfile; >>

Finally, class UserProfile contains: userId, profileId, name and application elements.

package com.base22.model; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; /** * @author Alex Arriaga * */ @XmlRootElement(name = "profile") @XmlAccessorType(XmlAccessType.FIELD) public class UserProfile < @XmlElement(name="profile_id") private String profileId; @XmlElement(name="user_id") private String userId; @XmlElement(name="name") private String name; @XmlElement(name="application") private String application; public UserProfile()< >public UserProfile(String userId, String name, String application) < this.userId = userId; this.profileId = "profile" + this.userId; this.name = name; this.application = application; >public String getProfileId() < return profileId; >public void setProfileId(String profileId) < this.profileId = profileId; >public String getUserId() < return userId; >public void setUserId(String userId) < this.userId = userId; >public String getName() < return name; >public void setName(String name) < this.name = dealerName; >public String getApplication() < return application; >public void setApplication(String application) < this.application = application; >>

3) As you can see, it’s very easy to add an XML attribute to your Java class, just type the annotation “@XmlAttribute” and JAXB will create your attribute automatically.

@XmlAttribute(name="current") private String currentUserProfile;

Источник

Читайте также:  Socket io react typescript
Оцените статью