Home > Blockchain >  How I can merge 2 XML strings into 1 in GOLANG
How I can merge 2 XML strings into 1 in GOLANG

Time:07-19

I would like to merge 2 XML files into 1 new file. first XML is schemaDtd and second XML is standard XML file with values , I want to merge them together into 1 new file.

my problem is that each XML start with "<?xml version='1.0' encoding..." so I can't concatenate both files into 1 new file, (get wrong format on the second part that start with "<?xml version..")

so i try to merge them with this code , but i got error :

this is my code

var xml1 map[string]interface{}
var xml2 map[string]interface{}

err1 := xml.Unmarshal([]byte(DTDSchema), &xml1)
err2 := xml.Unmarshal([]byte(xmlContent), &xml2)

maps.Merge(xml2, xml1)

fileContent , err := xml.Marshal(&xml1)

- this is the errors :

err1 : Error on unmarshal EOF ,

err2 : Error on unmarshal unknown type map[string]interface {},

Any idea ?

CodePudding user response:

It sounds like you want to take an XML file and give it an in-line/internal DTD.

You might find it easier to use a streaming/Sax-like parser to do what you want to do. That allows you to easily discard things you don't want (like processing instructions) as they're encountered.

CodePudding user response:

I leave here my solution for the next generations :-)

I found this package helpful: https://github.com/beevik/etree

sample code:

    // read xml 
    doc := etree.NewDocument()
    doc.ReadFromString(xmlContent)
    root := doc.Root()
    if root == nil {
        msg := "Get wrong xml content: "  xmlContent
        return errors.New(msg)
    }

    // read DTD 
    newXmldoc := etree.NewDocument()
    newXmldoc.ReadFromString(SchemaDTD)
    newXmldoc.SetRoot(root);
    newRoot := newXmldoc.Root();

// merge xml into DTD document 
    for _, e := range root.Child {
        newRoot.AddChild(e)
    }

    out, err := newXmldoc.WriteToString()
    if err != nil {
        return err
    }
    
    // here out cotain both DTD   xml from 2 diffrent string 
    
  • Related