如何从XML获取第一个属性?

时间:2014-02-25 14:33:26

标签: xml

如何序列化我的xml文件(没有foreach)后第一个问题? 我想在标签中获取QuestionText="2*2",在我的单选按钮中使用变体。

 public class Question
    {
        [XmlAttribute ("QuestionText") ] public string qstn;
        [XmlArrayItem("Variant")] public string[] Variants;
        [XmlArrayItem("Answer")] public string[] Answers;
    }
    public class Test
    {
        public List<Question> Questions = new List<Question>();

        public void SerializeToXML(string Path)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Test));
            TextWriter textWriter = new StreamWriter(Path);
            serializer.Serialize(textWriter, this);
            textWriter.Close();
        }

        public static Test DeserializeFromXML(string Path)
        {
            XmlSerializer deserializer = new XmlSerializer(typeof (Test));
            TextReader textReader = new StreamReader(Path);
            Test test;
            test = (Test) deserializer.Deserialize(textReader);
            textReader.Close();
            return test;
        }

我的XML:

<Question QuestionText="2*2">
  <Variants>
    <Variant>1</Variant>
    <Variant>4</Variant>
    <Variant>5</Variant>
  </Variants>
  <Answers>
    <Answer>4</Answer>
  </Answers>
</Question>
<Question QuestionText="3*2">
  <Variants>
    <Variant>1</Variant>
    <Variant>4</Variant>
    <Variant>5</Variant>
  </Variants>
  <Answers>
    <Answer>4</Answer>
    <Answer>number</Answer>
  </Answers>
</Question>
<Question QuestionText="4*2">
  <Variants>
    <Variant>1</Variant>
    <Variant>8</Variant>
  </Variants>
  <Answers>
    <Answer>4</Answer>
    <Answer>somenumber</Answer>
    <Answer>anynumber</Answer>
  </Answers>
</Question>

1 个答案:

答案 0 :(得分:0)

试试这个...

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

//使用工厂获取文档构建器的实例

DocumentBuilder db = dbf.newDocumentBuilder();

//使用构建器解析以获取XML文件的DOM表示

dom = db.parse(“你的xml”);

元素documentElement = dom.getDocumentElement();

//获取Employee元素的节点列表
   NodeList employeeNodeList = documentElement.getElementsByTagName(“Question”);

//第一个元素   employeeNodeList.item(0);