如何解析字符串格式的xml到数组?

时间:2019-02-13 13:40:25

标签: java string

有这样的String格式的xml:

<Users>
  <User> 
      <name>Alex</name>  
      ...other info
  </User>
  <User>
      <name>Natasha</name>
      ...other info
  </User>
</Users>

如何将这样的字符串拆分为字符串数组?

我的常见任务是,获取输入xml,按元素拆分,然后将每个元素序列化并分别保存在数据库中。因此,对于我的任务SAX,可能只有Pattern和Matcher。

2 个答案:

答案 0 :(得分:1)

Sax解析器是我的最爱,您可以尝试:Oracle

这是来自tutorialspoint.com

的示例xml解析代码示例

答案 1 :(得分:1)

假设您想要类似

的输出
f = Figure(figsize=(5,5), dpi=100)
ax=[]
lines=[0 for x in range(7)]
for i in range(0,7):
    ax.append(f.add_subplot(4,2,1+i))
    ax[i].set_autoscaley_on(True)
    ax[i].set_autoscalex_on(True)
    lines[i],=ax[i].plot([],[])

ser = serial.Serial('COM3', 115200) # Establish the connection on a specific port

Setup={"P_gain_X":0.0, "I_gain_X":0.0, "D_gain_X":0.0, "Set_point_X":0.0,
       "P_gain_Y":0.0, "I_gain_Y":0.0, "D_gain_Y":0.0, "Set_point_Y":0.0,
       "P_gain_Z":0.0, "I_gain_Z":0.0, "D_gain_Z":0.0, "Set_point_Z":0.0}

previous_time=datetime.datetime.now()

def update_line(hl, new_datax, new_datay):
    hl.set_xdata(numpy.append(hl.get_xdata(), new_datax))
    hl.set_ydata(numpy.append(hl.get_ydata(), new_datay)) 


def animate(i):
    global previous_time
    ser.write("R".encode('utf-8')) # send the command to arduino to receive the floats in return
    time= datetime.datetime.now()
    print ((time-previous_time)/1000) #just printing the time between 2 calls for debug
    previous_time = time

    for j in range(0,7):
        new_value,=struct.unpack("<f",ser.read(4)) #get float from arduino
        update_line(lines[j], time, new_value)
        ax[j].relim()
        ax[j].autoscale_view()
        #mplcursors.cursor(lines[j])

    f.canvas.draw()
    f.canvas.flush_events()


class DisplayPID(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        tk.Tk.wm_title(self, "Display and change PID")

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (StartPage, GraphPage):

            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text=("""Welcome"""), font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button1 = ttk.Button(self, text="Graph_Page",
                            command=lambda: controller.show_frame(GraphPage))
        button1.pack()



class GraphPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Graph Page", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button1 = ttk.Button(self, text="Back to Home",
                            command=lambda: controller.show_frame(StartPage))
        button1.pack()

        canvas=FigureCanvasTkAgg(f,self)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        toolbar = NavigationToolbar2Tk(canvas, self)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)



if __name__ == "__main__":

    Start = DisplayPID()
    ani = animation.FuncAnimation(f, animate, interval=100)
    Start.mainloop()

来自XML文件:

names[] = {"Alex", "Natasha"};

您可以使用JacksonXML解析器来获取所有用户的名称。 我已经为RootElement使用了Users类

<Users>
  <User> 
      <name>Alex</name>  
      <city>New York</city> 
  </User>
  <User>
      <name>Natasha</name>
      <city>New Jersey</city> 
  </User>
</Users>

和内部用户块的User类

@JacksonXmlRootElement(localName = "Users")
public class Users {    
    @JacksonXmlProperty(isAttribute=false, localName="User")
    @JacksonXmlElementWrapper(useWrapping = false)
    private List<User> user;
    public List<User> getUsers() {
        return user;
    }
    public void setUsers(List<User> users) {
        this.user = users;
    }   
}

,然后将XML文件读取为:

public class User {
    @JacksonXmlProperty(isAttribute=false, localName="name")
    private String name;
    @JacksonXmlProperty(isAttribute=false, localName="city")
    private String city;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
}