读取xml并将其存储在字符串中

时间:2013-07-02 06:48:30

标签: c# xml

我想阅读x,y,angle,direction,file

的值
<DESCIONTREE>

  <Motion X="296" Y="88" Angle="-90" Direction="up" file="2.jpg" />
  <Motion X="384" Y="94" Angle="90" Direction="down" file="2.jpg" />
  <Motion X="480" Y="94" Angle="90" Direction="down" file="2.jpg" />
  <Motion X="272" Y="106" Angle="90" Direction="down" file="2.jpg" />

</DESCIONTREE>

string contents = File.ReadAllText("test.xml");

          XmlDocument xml = new XmlDocument();
            xml.LoadXml(contents);  // suppose that str string contains "<Names>...</Names>"

            XmlNodeList xnList = xml.SelectNodes("/DESCIONTREE/Motion");

            foreach (XmlNode xn in xnList)
            {
               // Console.WriteLine(xn.InnerText);

                richTextBox1.AppendText(xn.OuterXml+ "\n");
            }

但我想存储每个变量:

String x,y,angle,direction,file ;

9 个答案:

答案 0 :(得分:5)

使用Linq到Xml,您可以轻松地解析xml并创建具有x,y,角度,方向和文件的强类型属性的匿名“运​​动”对象列表:

XDocument xdoc = XDocument.Load("test.xml")
var motions = from m in xdoc.Root.Elements("Motion")
              select new {
                  X = (int)m.Attribute("X"),
                  Y = (int)m.Attribute("Y"),
                  Angle = (int)m.Attribute("Angle"),
                  Direction = (string)m.Attribute("Direction"),
                  File = (string)m.Attribute("file")
              };

 foreach(var motion in motions)
 {
    // use motion
    Console.WriteLine(motion); // Dumps all object values
    Console.WriteLine(motion.Angle); // Writes angle value
 }

答案 1 :(得分:2)

为什么不使用linq2xml

XElement doc=XElement.Load("yourXml.xml");
var lst=doc.Elements("Motion")
   .Select(x=>
        new
       {
         X=x.Attribute("X").Value,
         Y=x.Attribute("Y").Value,
         Angle=x.Attribute("Angle").Value,
       }).ToList();

现在你可以迭代lst

foreach(var l in lst)
{
    l.X;
    l.Y;
    l.Angle;
}

答案 2 :(得分:1)

根据研究和我的实验,我得到了这个。:

我可以直接访问属性:

XmlDocument xml = new XmlDocument();
xml.LoadXml(@"
<DESCIONTREE>
  <Motion X='296' Y='88' Angle='-90' Direction='up' file='2.jpg' />
  <Motion X='384' Y='94' Angle='90' Direction='down' file='2.jpg' />
</DESCIONTREE>
");

XmlNodeList xnList = xml.SelectNodes("/DESCIONTREE/Motion");


foreach (XmlNode xn in xnList)
{
    Console.WriteLine("{0} {1} {2} {3} {4}", xn.Attributes["X"].Value, xn.Attributes["Y"].Value, xn.Attributes["Angle"].Value, xn.Attributes["Direction"].Value, xn.Attributes["file"].Value);
}

或者声明一个类,然后使用反序列化。

答案 3 :(得分:1)

这是我的班级示例

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main extends JFrame {
/**
 * 
*/
 private static final long serialVersionUID = 1L;
 JButton button;

public static void main(String[] args) {
    // TODO Auto-generated method stub
    new Main();
}

public GraphModel model = new GraphModel();
public GraphView view;

public Main() {
    setPreferredSize(new Dimension(600, 600));
    setLocation(100, 100);
    setLayout(new BorderLayout());
    setTitle("Exam prac");

    view = new GraphView(model);
    button = new JButton("Button");
    add("North", button);

    pack();
    setVisible(true);
}
}

答案 4 :(得分:1)

这是另一个类示例

import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Vector;

import javax.swing.*;

public class GraphView extends JPanel implements MouseListener, MouseMotionListener, GraphChangeListener 
{
private static final long serialVersionUID = 1L;
private GraphModel graph;

public GraphView(final GraphModel graph)
{
    // call inherited constructor (JPanel's)
    super();

    this.graph = graph;

    addMouseMotionListener(this);
    addMouseListener(this);

    graph.addListener(this);

    setLayout(null);
}

@Override
protected void paintComponent(Graphics g) {
    // call inherited paint - which clears the background
    super.paintComponent(g);

}

@Override
public void graphChanged(GraphModel model) {
    // TODO Auto-generated method stub

}

@Override
public void mouseDragged(MouseEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void mouseMoved(MouseEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void mouseClicked(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseReleased(MouseEvent arg0) {
    // TODO Auto-generated method stub

}


}

答案 5 :(得分:0)

这是我的GraphModel类

public class GraphModel 
{

GraphChangeListenerQue listenerQ = new GraphChangeListenerQue();

public void fireGraphChange()
{
    listenerQ.fireGraphChanged(this);
}


public void addListener(GraphChangeListener listener)
{
    listenerQ.addListener(listener);
}

}

答案 6 :(得分:0)

GChangeQue类

import java.util.ArrayList;

public class GraphChangeListenerQue {
ArrayList<GraphChangeListener> listeners = new ArrayList<GraphChangeListener>();

public void addListener(GraphChangeListener listener) {
    if (!listeners.contains(listener)) {
        listeners.add(listener);
    }
}

public void fireGraphChanged(GraphModel source) {
    for (GraphChangeListener listener : listeners) {
        listener.graphChanged(source);
    }
}

}

答案 7 :(得分:0)

GChangeL类

public interface GraphChangeListener 
{
    void graphChanged(GraphModel model);
}

答案 8 :(得分:0)

主类示例

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.FileOutputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Vector;

    import javax.swing.BorderFactory;
    import javax.swing.DefaultListModel;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListCellRenderer;
    import javax.swing.border.Border;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.table.DefaultTableModel;
    import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;

public class Main extends JFrame implements ActionListener,
    ListCellRenderer<String> {
/**
 * 
 */
private static final long serialVersionUID = 1L;
static Main m;

Connection con = null;
Statement stmt = null;
Vector<String> studNumbers;
DefaultListModel<String> listmodel;
JList<String> numberlist;
DefaultTableModel tablemodel;

JTable table;
JLabel studnums;
JLabel surnames;
JLabel initialss;
JButton conbtn;
JButton disc;
JButton exp;

String selected; // currently selected student number.
String filename;
String CurYear = "";
JScrollPane scrollpane;

Document doc;
Element studyrecord;
Element yearofstudy;

ResultSet resultset;

public static void main(String[] args) {
    // TODO Auto-generated method stub
    m = new Main();
    m.setDefaultCloseOperation(EXIT_ON_CLOSE);

}

public Main() {
    BuildUI();
    setBounds(100, 100, 685, 600);
    pack();
    setVisible(true);

}

private void BuildUI() {
    setTitle("Study Records");
    setLayout(new BorderLayout());
    setBackground(Color.gray);

    JPanel top = new JPanel();
    top.setBackground(Color.DARK_GRAY);
    top.setOpaque(true);

    conbtn = new JButton("Connect");
    conbtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            connect();
            Vector<String> tempV = new Vector<String>();
            tempV = populateList();
            for (int x = 0; x <= tempV.size() - 1; x++) {
                listmodel.addElement(tempV.get(x));
            }
            conbtn.setEnabled(false);
            disc.setEnabled(true);
        }
    });

    disc = new JButton("Disconnect");
    disc.setEnabled(false);
    disc.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            disconnectDB();
            disc.setEnabled(false);
            conbtn.setEnabled(true);
            table.setModel(new DefaultTableModel());
            surnames.setText("");
            studnums.setText("");
            initialss.setText("");
            numberlist.setModel(new DefaultListModel<String>());
        }
    });
    exp = new JButton("Export");
    exp.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            savetoXML();
        }
    });

    top.setLayout(new FlowLayout());
    top.add(conbtn);
    top.add(disc);
    top.add(exp);
    add("North", top);

    JPanel left = new JPanel();
    left.setPreferredSize(new Dimension(200, 0));
    left.setLayout(new BorderLayout());
    JLabel SN = new JLabel("Student Numbers");
    left.add("North", SN);

    // List
    listmodel = new DefaultListModel<String>();
    numberlist = new JList<String>(listmodel);
    JScrollPane scroll = new JScrollPane(numberlist);

    // Cell Rendering
    numberlist.setCellRenderer(this);
    numberlist.addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            // TODO Auto-generated method stub
            if (e.getValueIsAdjusting()) {
                selected = numberlist.getSelectedValue();
                studnums.setText(selected);
                ResultSet result = getStudent(selected);
                try {
                    while (result.next()) {
                        surnames.setText(result.getString("Surname"));
                        initialss.setText(result.getString("Initials"));
                    }
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

            }

            tablemodel = (DefaultTableModel) table.getModel();
            tablemodel.getDataVector().removeAllElements();
            tablemodel.fireTableDataChanged();
            populateTable(selected);
            table.setModel(tablemodel);
        }
    });

    left.add("Center", scroll);
    add("West", left);

    JPanel center = new JPanel();
    center.setLayout(new BorderLayout());
    JPanel right = new JPanel();
    right.setLayout(new GridLayout(3, 2));

    JLabel studnum = new JLabel("Student Number:");
    JLabel surname = new JLabel("Surname:");
    JLabel initials = new JLabel("Initials:");

    studnums = new JLabel("");
    surnames = new JLabel("");
    initialss = new JLabel("");

    right.add(studnum);
    right.add(studnums);
    right.add(surname);
    right.add(surnames);
    right.add(initials);
    right.add(initialss);

    center.add("North", right);
    add(center);

    // table
    tablemodel = new DefaultTableModel();
    tablemodel.addColumn(new String("Year"));
    tablemodel.addColumn(new String("ModuleCode"));
    tablemodel.addColumn(new String("ModuleName"));
    tablemodel.addColumn(new String("Mark"));

    table = new JTable(tablemodel);
    scrollpane = new JScrollPane(table);
    center.add("Center", scrollpane);

    // XML
    try {
        doc = createDoc();
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    studyrecord = doc.createElement("StudyRecord");
    // yearofstudy = doc.createElement("YearofStudy");

}

public String getfilename() {
    // filename =
    // "C:\\Users\\user\\Desktop\\WRAP301\\WRAP pracs\\Prac 11.MyStudyRecords.mdb";
    JFileChooser dlgOpen = new JFileChooser();

    if (dlgOpen.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        filename = dlgOpen.getSelectedFile().getAbsolutePath();
        System.out.println(filename);
        return filename;
    }
    return null;
}

public String savefilename() {
    JFileChooser dlgOpen = new JFileChooser();

    if (dlgOpen.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
        filename = dlgOpen.getSelectedFile().getAbsolutePath();
        System.out.println(filename);
        return filename;
    }
    return null;
}

public void connect() {
    System.out.println("Establishing connection to database...");

    System.out.println("   Loading ODBC driver for MS Access database...");
    try {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    } catch (Exception e) {
        System.out.println("   Unable to load ODBC driver...");
        return;
    }

    System.out
            .println("   Use ODBC driver to connect to MS Access database (students.mdb)...");
    try {
        System.out.println("   Locate database to open...");

        String file = m.getfilename();
        System.out.println(file);
        String myDB = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="
                + file;
        System.out.println("      Connection string = " + myDB);

        // create connection to DB
        con = DriverManager.getConnection(myDB, "", "");

        // create statement object for manipulating DB
        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                ResultSet.CONCUR_UPDATABLE);
    } catch (Exception e) {
        System.out
                .println("   Unable to connect to DB..." + e.getMessage());
    }

    System.out.println();
}

public void disconnectDB() {
    System.out.println("Disconnecting from database...");

    try {
        // Important to close connection (same as with files)
        con.close();
    } catch (Exception ex) {
        System.out.println("   Unable to disconnect from database");
    }
}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

}

public Vector<String> populateList() {
    Vector<String> list = new Vector<String>();
    try {
        String sql = "SELECT * FROM students";
        System.out.println("   Performing query, sql = " + sql);
        ResultSet result = stmt.executeQuery(sql);
        System.out.println();
        while (result.next()) {
            String studNo = result.getString("StudentNo");
            list.add(studNo);
        }
        return list;
    } catch (Exception e) {
        return null;
    }
}

public ResultSet getStudent(String student) {
    try {
        String sql = "SELECT students.StudentNo, students.Surname, students.Initials, takes.Year, takes.Mark, modules.ModuleCode, modules.ModuleName FROM students INNER JOIN (modules INNER JOIN takes ON modules.[ModuleCode] = takes.[ModuleCode]) ON students.[StudentNo] = takes.[StudentNumber] WHERE (((students.StudentNo)="
                + student + "))";
        System.out.println("   Performing query, sql = " + sql);
        ResultSet result = stmt.executeQuery(sql);
        System.out.println(result.toString());
        return result;
    } catch (Exception e) {
        e.getMessage();
        return null;
    }
}

public void populateTable(String studNum) {
    ResultSet tempset = getStudent(selected);

    try {
        while (tempset.next()) {
            Vector<String> tempV = new Vector<String>();

            tempV.addElement(tempset.getString("Year"));
            tempV.addElement(tempset.getString("ModuleCode"));
            tempV.addElement(tempset.getString("ModuleName"));
            tempV.addElement(tempset.getString("Mark"));

            tablemodel.addRow(tempV);
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void savetoXML() {

    Element report = doc.createElement("Report");
    Element student = createStudent(doc);
    ResultSet studentsetR = getStudent(selected);
    Element studyrecord = null;
    String year = "";
    // int x=1;
    try {
        while (studentsetR.next()) {
            // System.out.println(studentsetR.getArray(x).toString());
            CurYear = studentsetR.getString("Year");
            year = CurYear;
            Element yearofstudy = doc.createElement("Yearofstudy");
            studyrecord = createStudyrecord(yearofstudy, studentsetR,
                    CurYear);
            // x++;

        }
    } catch (SQLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    report.appendChild(student);
    report.appendChild(studyrecord);
    doc.appendChild(report);

    try {
        saveDoc(doc, savefilename());
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public Document createDoc() throws Exception {
    // create DocumentBuilder to parse XML document
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    // create empty document
    Document doc = builder.newDocument();

    return doc;
}

public Element createStudent(Document doc) {
    Element student = doc.createElement("student");
    Element studnum = doc.createElement("studnum");
    Element surname = doc.createElement("surname");
    Element initials = doc.createElement("initials");

    ResultSet studentresult = getStudent(selected);

    try {
        while (studentresult.next()) {
            studnum.appendChild(doc.createTextNode((studentresult
                    .getString("StudentNo"))));
            surname.appendChild(doc.createTextNode(studentresult
                    .getString("Surname")));
            initials.appendChild(doc.createTextNode(studentresult
                    .getString("Initials")));
            break;
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    student.appendChild(studnum);
    student.appendChild(surname);
    student.appendChild(initials);
    return student;
}

public Element createStudyrecord(Element yearofstudy, ResultSet studentSet,
        String Year) {

    // Element yearofstudy = doc.createElement("YearOfStudy");
    Element module = doc.createElement("module");

    try {
        Year = studentSet.getString("Year");
        yearofstudy.setAttribute("year", CurYear);

        yearofstudy.appendChild(module);
        module.setAttribute("code", studentSet.getString("ModuleCode"));
        module.setAttribute("mark", studentSet.getString("Mark"));
        module.setAttribute("name", studentSet.getString("ModuleName"));
        studyrecord.appendChild(yearofstudy);

        return studyrecord;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

public void saveDoc(Document doc, String filename) throws Exception {
    // obtain serializer
    DOMImplementation impl = doc.getImplementation();
    DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature(
            "LS", "3.0");
    LSSerializer ser = implLS.createLSSerializer();
    ser.getDomConfig().setParameter("format-pretty-print", true);

    // create file to save too
    FileOutputStream fout = new FileOutputStream(filename);

    // set encoding options
    LSOutput lsOutput = implLS.createLSOutput();
    lsOutput.setEncoding("UTF-8");

    // tell to save xml output to file
    lsOutput.setByteStream(fout);

    // FINALLY write output
    ser.write(doc, lsOutput);

    // close file
    fout.close();

    // display output on screen to see (note UTF-16 at top)
    // System.out.println(ser.writeToString(doc));
}

public Component getListCellRendererComponent(JList<? extends String> list,
        String value, int index, boolean isSelected, boolean cellHasFocus) {
    Border blackline = BorderFactory.createLineBorder(Color.black);
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());

    ResultSet set = getStudent(value);

    JLabel studnum_label = new JLabel("Stud number:");
    JLabel surname_label = new JLabel("Surname:");
    JLabel initials_label = new JLabel("Initials:");
    JLabel yos_label = new JLabel("Year of study:");

    System.out.println("value:" + value);
    JLabel studnum = new JLabel(value);
    JLabel surname = new JLabel("");
    JLabel initials = new JLabel("");
    JLabel yearofStudy = new JLabel("");

    try {
        while (set.next()) {
            surname = new JLabel(set.getString("Surname"));
            System.out.println("here");
            initials = new JLabel(set.getString("Initials"));
            // set.last();
            yearofStudy = new JLabel(set.getString("Year"));
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    JPanel center = new JPanel(new GridLayout(4, 2));

    center.add(studnum_label);
    System.out.println("studnum value before adding: " + studnum.getText());
    center.add(studnum);
    center.add(surname_label);
    System.out.println("surname value before adding: " + surname);
    center.add(surname);
    center.add(initials_label);
    center.add(initials);
    center.add(yos_label);
    center.add(yearofStudy);

    if (isSelected) {
        studnum_label.setForeground(Color.blue);
        surname_label.setForeground(Color.blue);
        initials_label.setForeground(Color.blue);
        yos_label.setForeground(Color.blue);
        studnum.setForeground(Color.blue);
        surname.setForeground(Color.blue);
        initials.setForeground(Color.blue);
        yearofStudy.setForeground(Color.blue);
    }
    if (cellHasFocus) {
        studnum_label.setForeground(Color.red);
        surname_label.setForeground(Color.red);
        initials_label.setForeground(Color.red);
        yos_label.setForeground(Color.red);
        studnum.setForeground(Color.red);
        surname.setForeground(Color.red);
        initials.setForeground(Color.red);
        yearofStudy.setForeground(Color.red);
    }

    JLabel title = new JLabel("Student Card");
    JLabel image = new JLabel(new ImageIcon("earth.jpg"));

    panel.add(BorderLayout.NORTH, title);
    panel.setBorder(blackline);
    panel.add(BorderLayout.WEST, image);
    panel.add(BorderLayout.CENTER, center);

    return panel;
}
}