From f7d5416bafe786b9eed8459efee8f52d09385d2f Mon Sep 17 00:00:00 2001 From: Dominic Ricottone Date: Sun, 16 Oct 2022 14:16:35 -0500 Subject: [PATCH] Fixing blockquotes This hacks on the unmarshaler to add an Order field, so that the paragraphs and quotes can be normalized and sorted. Still need to hack on the marshaler so that paragraphs and quotes can be passed together as an interface array. --- xml.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/xml.go b/xml.go index a1c3e58..e35c01a 100644 --- a/xml.go +++ b/xml.go @@ -3,6 +3,7 @@ package main import ( + "io" "encoding/xml" ) @@ -11,11 +12,13 @@ type Head struct { } type Paragraph struct { - Text string `xml:",innerxml"` + Text string `xml:",innerxml"` + Order int `xml:"-"` } type BlockQuote struct { - Paragraphs []Paragraph `xml:"p"` + Paragraphs []Paragraph `xml:"p"` + Order int `xml:"-"` } type Division struct { @@ -24,6 +27,49 @@ type Division struct { BlockQuotes []BlockQuote `xml:"blockquote"` } +func (d *Division) UnmarshalXML(decoder *xml.Decoder, start xml.StartElement) error { + counter := 0 + + for { + token, err := decoder.Token() + if err == io.EOF { + break + } + if err != nil { + return err + } + + switch token.(type) { + case xml.StartElement: + new_start := token.(xml.StartElement) + if (new_start.Name.Local == "p") { + target := Paragraph{} + decoder.DecodeElement(&target, &new_start) + + target.Order = counter + counter += 1 + + d.Paragraphs = append(d.Paragraphs, target) + } else if (new_start.Name.Local == "blockquote") { + target := BlockQuote{} + decoder.DecodeElement(&target, &new_start) + + target.Order = counter + counter += 1 + + d.BlockQuotes = append(d.BlockQuotes, target) + } else if (new_start.Name.Local == "div") { + target := Division{} + decoder.DecodeElement(&target, &new_start) + + d.Divisions = append(d.Divisions, target) + } + } + } + + return nil +} + type Body struct { Title string `xml:"h3"` Division Division `xml:"div"` -- 2.45.2