我有一個擁有 XML 的客戶,他們似乎想要一個庫存陣列,但每個專案都在另一個之后列出,沒有包裝節點。
這是我正在做的一個例子,但每個專案都有一個包裝節點。有沒有辦法讓它們在“根”下一個接一個地列出?
測驗代碼:
package main
import (
"encoding/xml"
"fmt"
"os"
"strconv"
)
func main() {
type InventoryItem struct {
XMLName xml.Name
ItemName string `xml:"Name"`
ItemDescription string `xml:"Description"`
}
type XMLEnvelop struct {
XMLName xml.Name `xml:"root"`
Inventory []InventoryItem `xml:"item"`
Records int `xml:"records"`
}
var items []InventoryItem
for i := 1; i < 6; i {
items = append(items, InventoryItem{XMLName: xml.Name{Local: "item" strconv.Itoa(i)}, ItemName: "Test " strconv.Itoa(i), ItemDescription: "Description " strconv.Itoa(i)})
}
v := &XMLEnvelop{Records: 1, Inventory: items}
output, err := xml.MarshalIndent(v, "", " ")
if err != nil {
fmt.Printf("error: %v\n", err)
}
// Write the output to check
os.Stdout.Write(output)
//Here is where I would make the request
}
測驗輸出:
<root>
<item1>
<Name>Test 1</Name>
<Description>Description 1</Description>
</item1>
<item2>
<Name>Test 2</Name>
<Description>Description 2</Description>
</item2>
<item3>
<Name>Test 3</Name>
<Description>Description 3</Description>
</item3>
<item4>
<Name>Test 4</Name>
<Description>Description 4</Description>
</item4>
<item5>
<Name>Test 5</Name>
<Description>Description 5</Description>
</item5>
<records>1</records>
</root>
去游樂場:https : //play.golang.org/p/3DRUABFEQvC
這是他們似乎正在尋找的輸出......無論出于何種原因。
<root>
<Name>Test 1</Name>
<Description>Description 1</Description>
<Name>Test 2</Name>
<Description>Description 2</Description>
<Name>Test 3</Name>
<Description>Description 3</Description>
<Name>Test 4</Name>
<Description>Description 4</Description>
<Name>Test 5</Name>
<Description>Description 5</Description>
<records>1</records>
</root>
uj5u.com熱心網友回復:
您可以實作自定義封送拆收器。
type InventoryItem struct {
XMLName xml.Name
ItemName string `xml:"Name"`
ItemDescription string `xml:"Description"`
}
func (i InventoryItem) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
// Ignore the passed in `start` argument, it represents the
// parent InventoryItem element of the Name and Description.
// Declare types to represent the elements you want to encode,
// initialize them to the item's field values and encode them.
//
// Use the ",chardata" option to tell the encoder to encode the
// field's value directly rather than as a child element.
type Name struct {
Value string `xml:",chardata"`
}
if err := e.Encode(Name{i.ItemName}); err != nil {
return err
}
type Description struct {
Value string `xml:",chardata"`
}
return e.Encode(Description{i.ItemDescription})
}
https://play.golang.org/p/D4ZVr2sWZju
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/351774.html
上一篇:在C 中從陣列列印值
