Skip to content

Commit

Permalink
XML Decoder: Fixed processing comments in empty XML #1446
Browse files Browse the repository at this point in the history
  • Loading branch information
mikefarah committed Nov 27, 2022
1 parent 68f47c0 commit 77998d1
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
15 changes: 12 additions & 3 deletions pkg/yqlib/decoder_xml.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ func (dec *xmlDecoder) createMap(n *xmlNode) (*yaml.Node, error) {
yamlNode := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}

if len(n.Data) > 0 {
log.Debug("creating content node for map")
label := dec.prefs.ContentName
labelNode := createScalarNode(label, label)
labelNode.HeadComment = dec.processComment(n.HeadComment)
Expand Down Expand Up @@ -87,13 +88,21 @@ func (dec *xmlDecoder) createMap(n *xmlNode) (*yaml.Node, error) {
return nil, err
}
} else {
log.Debug("before hack, this is the data len: %", len(children[0].Data))
// comment hack for maps of scalars
// if the value is a scalar, the head comment of the scalar needs to go on the key?
// add tests for <z/> as well as multiple <ds> of inputXmlWithComments > yaml
if len(children[0].Children) == 0 && children[0].HeadComment != "" {
log.Debug("scalar comment hack")
labelNode.HeadComment = labelNode.HeadComment + "\n" + strings.TrimSpace(children[0].HeadComment)
children[0].HeadComment = ""
if len(children[0].Data) > 0 {

log.Debug("scalar comment hack")
labelNode.HeadComment = labelNode.HeadComment + "\n" + strings.TrimSpace(children[0].HeadComment)
children[0].HeadComment = ""
} else {
// child is null, put the headComment as a linecomment for reasons
children[0].LineComment = children[0].HeadComment
children[0].HeadComment = ""
}
}
valueNode, err = dec.convertToYamlNode(children[0])
if err != nil {
Expand Down
5 changes: 5 additions & 0 deletions pkg/yqlib/xml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,11 @@ var xmlScenarios = []formatScenario{
input: "<root> <!-- comment-->value</root>",
expected: "\n# comment\nroot: value\n", //needs fix
},
{
skipDoc: true,
input: "<root> <!-- comment--></root>",
expected: "root: # comment\n",
},
{
skipDoc: true,
input: "<root>value<!-- comment-->anotherValue </root>",
Expand Down

0 comments on commit 77998d1

Please sign in to comment.