Skip to content

Commit

Permalink
Skip empty attribute values when serializing XML processing instructions
Browse files Browse the repository at this point in the history
Fixes #770
  • Loading branch information
jhy committed Jul 14, 2021
1 parent d3922f5 commit fce241b
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
3 changes: 3 additions & 0 deletions CHANGES
Expand Up @@ -8,6 +8,9 @@ jsoup changelog

* Bugfix: when making a HTTP POST, if the request write fails, make sure the connection is immediately cleaned up.

* Bugfix: in the XML parser, XML processing instructions without attributes would be serialized as if they did.
<https://github.com/jhy/jsoup/issues/770>

* Bugfix: updated the HtmlTreeParser resetInsertionMode to the current spec for supported elements
<https://github.com/jhy/jsoup/issues/1491>

Expand Down
12 changes: 10 additions & 2 deletions src/main/java/org/jsoup/nodes/XmlDeclaration.java
Expand Up @@ -52,9 +52,17 @@ public String getWholeDeclaration() {

private void getWholeDeclaration(Appendable accum, Document.OutputSettings out) throws IOException {
for (Attribute attribute : attributes()) {
if (!attribute.getKey().equals(nodeName())) { // skips coreValue (name)
String key = attribute.getKey();
String val = attribute.getValue();
if (!key.equals(nodeName())) { // skips coreValue (name)
accum.append(' ');
attribute.html(accum, out);
// basically like Attribute, but skip empty vals in XML
accum.append(key);
if (!val.isEmpty()) {
accum.append("=\"");
Entities.escape(accum, val, out, true, false, false);
accum.append('"');
}
}
}
}
Expand Down
10 changes: 10 additions & 0 deletions src/test/java/org/jsoup/parser/XmlTreeBuilderTest.java
Expand Up @@ -152,6 +152,16 @@ public void testParseDeclarationAttributes() {
assertEquals("<?xml version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", decl.outerHtml());
}

@Test
public void testParseDeclarationWithoutAttributes() {
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<?myProcessingInstruction My Processing instruction.?>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
XmlDeclaration decl = (XmlDeclaration) doc.childNode(2);
assertEquals("myProcessingInstruction", decl.name());
assertTrue(decl.hasAttr("My"));
assertEquals("<?myProcessingInstruction My Processing instruction.?>", decl.outerHtml());
}

@Test
public void caseSensitiveDeclaration() {
String xml = "<?XML version='1' encoding='UTF-8' something='else'?>";
Expand Down

0 comments on commit fce241b

Please sign in to comment.