简体   繁体   English

QT5 C ++ QByteArray XML解析器

[英]QT5 C++ QByteArray XML Parser

I get the following xml 我得到以下xml

<Tra Type="SomeText">   
   <tr>Abcdefghij qwertzu</tr>
   <Rr X="0.0000" Y="0.0000" Z="0.0000" A="0.0000" B="0.0000" C="0.0000" />
   <Ar A1="0.0000" A2="0.0000" A3="0.0000" A4="0.0000" A5="0.0000" A6="0.0000" />
   <Er E1="0.0000" E2="0.0000" E3="0.0000" E4="0.0000" E5="0.0000" E6="0.0000" />
   <Te T21="1.09" T22="2.08" T23="3.07" T24="4.06" T25="5.05" T26="6.04" T27="7.03" T28="8.02" T29="9.01" T210="10.00" />
   <D>125</D>
   <IP></IP>
</Tra>

through a socket that saves it in a QByteArray called Data. 通过将其保存在名为Data的QByteArray中的套接字。

I want to extract and save every value from the xml to different variables (some as Integers some as QString's). 我想从xml中提取每个值并将其保存到不同的变量中(有些是整数,有些是QString)。

My main problem is that I dont know how to distinguish xml strings like <D>125</D> with a value in between the Tags and xml strings like <Te T210="10.00" T29="9... /> that got the value in the Tag-String itself. 我的主要问题是,我不知道如何在标签和xml字符串(如<Te T210="10.00" T29="9... />之间用一个值来区分<D>125</D>这样的xml字符串<Te T210="10.00" T29="9... />在Tag-String本身中得到了值。

My code looks like this so far: 到目前为止,我的代码如下:

QByteArray Data = socket->readAll();

QXmlStreamReader xml(Data);
while(!xml.atEnd() && !xml.hasError())
{
.....  
}

There's just so many examples already, aren't there? 已经有很多例子了,不是吗? =( =(

Anyway, like Frank said, if you want to read data (characters) from within tags - use QXmlStreamReader::readElementText . 无论如何,就像Frank所说的那样,如果您想从标签中读取数据(字符),请使用QXmlStreamReader :: readElementText

Alternatively, you can do this: 或者,您可以执行以下操作:

QXmlStreamReader reader(xml);
while(!reader.atEnd())
{  
  if(reader.isStartElement())
  {
    if(reader.name() == "tr")
    {
      reader.readNext();

      if(reader.atEnd()) 
        break;

      if(reader.isCharacters())
      {
        // Here is the text that is contained within <tr>
        QString text = reader.text().toString();
      }
    }
  }

  reader.readNext();
}

For attributes, you should use QXmlStreamReader::attributes which will give you a container-type class of attributes . 对于属性,应该使用QXmlStreamReader :: attributes ,它将为您提供容器类型的attribute类。

QXmlStreamReader reader(xml);
while(!reader.atEnd())
{  
  if(reader.isStartElement())
  {
    if(reader.name() == "Rr")
    {
      QXmlStreamAttributes attributes = reader.attributes();
      // This doesn't check if the attribute exists... just a warning.
      QString x = attributes.value("X").toString();
      QString y = attributes.value("Y").toString();
      QString a = attributes.value("A").toString();
      // etc...
    }
  }

  reader.readNext();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM