Reputation: 304
i want to assign xml tag contents to string:-
String str=
"
<?xml version="1.0" encoding="UTF-8"?>
<PrintLetterBarcodeData uid="s3434343" name="sdsdasdasd" gender="M" yob="1991" co="S/sdsds" street="sdsdsdl605"/>
";
but there are few errors. I am using eclipse. this tag automatically generated by QR code scanner,hence i can not modify this tag.
Upvotes: 0
Views: 8469
Reputation: 3504
To get the values of the data, you should use some kind of xml parser.
since Java 1.6 you can use JAXB for this task:
@XmlRootElement( name = "PrintLetterBarcodeData" )
@XmlAccessorType(XmlAccessType.FIELD)
public class PrintLetterBarcodeData
{
enum Gender
{
M, F
}
@XmlAttribute
String uid;
@XmlAttribute
String name;
@XmlAttribute
Gender gender;
@XmlAttribute( name = "yob" )
int yearOfBirth;
@XmlAttribute
String co;
@XmlAttribute
String street;
// getters/setters omitted for readability, these should be used in production code
}
private static PrintLetterBarcodeData parse( String xml ) throws JAXBException
{
Unmarshaller unmarshaller = JAXBContext.newInstance( PrintLetterBarcodeData.class ).createUnmarshaller();
return (PrintLetterBarcodeData) unmarshaller.unmarshal( new StringReader( xml ) );
}
private static void sample() throws JAXBException
{
String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <PrintLetterBarcodeData uid=\"s3434343\" name=\"sdsdasdasd\" gender=\"M\" yob=\"1991\" co=\"S/sdsds\" street=\"sdsdsdl605\"/>";
PrintLetterBarcodeData barcodeData = parse( str );
System.out.println( barcodeData.uid );
System.out.println( barcodeData.name );
System.out.println( barcodeData.gender );
System.out.println( barcodeData.yearOfBirth );
System.out.println( barcodeData.co );
System.out.println( barcodeData.street );
}
you can then use it like any normal java object.
Upvotes: 1
Reputation: 3592
How do you put the text into eclipse, pasting from clipboard?
In that case try Preferences/Java/Editor/Typing/ "Escape text when pasting into a string literal"
.
If you read String from otyher source you can try with http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html
Upvotes: 0
Reputation: 777
You need to escape all the double-quotes:
String str="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <PrintLetterBarcodeData uid=\"s3434343\" name=\"sdsdasdasd\" gender=\"M\" yob=\"1991\" co=\"S/sdsds\" street=\"sdsdsdl605\"/>";
Upvotes: 2
Reputation: 1003
What are the errors? It is hard to diagnose it without knowing the errors. However, I can say that you will need a \ character before the quotes inside the XML string.
It would be
String str= "<?xml version=\"1.0\" encoding=\"UTF-8\"?><PrintLetterBarcodeData uid=\"s3434343\" name=\"sdsdasdasd\" gender=\"M\" yob=\"1991\" co=\"S/sdsds\" street=\"sdsdsdl605\"/>";
Upvotes: 1