In golang, when reading xml files, you often encounter problems with the xml file header (i.e. ), which may cause the parsing of the xml file to fail.
The following introduces several methods to remove the xml header.
We can use thestrings.Trim
function to remove the xml header, the code is as follows:
func removeXmlHeader(xmlContent string) string { return strings.Trim(xmlContent, "") }
In the above code, we use thestrings.Trim
function to remove the first three special characters (i.e. BOM characters, whose ASCII code is
) in xmlContent, so that xml header.
Another way to remove the xml header is to use thexml.Decoder
object to read the xml file and usedecoder.Token
The function obtains the Token object in the xml file. If the Token is a declaration tag (i.e.
), we can skip it before parsing the xml file. The code is as follows:
func removeXmlHeader(xmlContent string) (string, error) { decoder := xml.NewDecoder(strings.NewReader(xmlContent)) var result strings.Builder for { token, err := decoder.Token() if err == io.EOF { break } if err != nil { return "", err } switch t := token.(type) { case xml.ProcInst: if t.Target == "xml" { continue } } result.WriteString(fmt.Sprintf("%v", token)) } return result.String(), nil }
In the above code, we create an xml .Decoder object, and then use thedecoder.Token
function to read the Token object from the xml file. If the read Token object is a declaration tag (i.e. xml.ProcInst), we determine whether its target is xml. If so, skip this Token object. Otherwise, continue to read the next Token object until the entire xml file is read.
When we put the Token object into the strings.Builder object, we can return the processed xml string.
The third method to remove the xml header is to usexml.Unmarshal
to skip the xml header when parsing the xml file.
func removeXmlHeader(xmlContent string, v interface{}) error { xmlContent = strings.Trim(xmlContent, "") return xml.Unmarshal([]byte(xmlContent), v) }
In the above code, we remove the xml file header through thestrings.Trim
function, and then call thexml.Unmarshal
function to parse the xml file to the target object, so that the xml header can be easily removed.
To sum up, the above are three methods to remove the XML header. Which method to choose depends on the specific business needs. When using these methods, you need to pay attention to the characteristics of each method in order to choose the appropriate method to solve the problem.
The above is the detailed content of golang remove xml header. For more information, please follow other related articles on the PHP Chinese website!