XMLReader-如何读取此元素/节点模式

时间:2018-08-25 22:53:47

标签: xml xmlreader

这是我需要能够阅读的一些XML。我需要获取分配给某些变量的每个功能的QualitySetting值:

import React from 'react';
import { Alert,Platform,StyleSheet, Text, View } from 'react-native';
import { Constants, Location, Permissions } from 'expo';

import AppStackNav from '../party/src/nav/appStackNav';


import Geocoder from 'react-native-geocoding';

Geocoder.init('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');

export default class App extends React.Component {
  state = {
    location: null,
    errorMessage: null,
    addressComponent: null,
  };

  componentWillMount() {
    this._getLocationAsync();
  } 

  _getLocationAsync = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    if (status !== 'granted') {
      this.setState({
        errorMessage: 'Permission to access location was denied',
      });
    }
    let location = await Location.getCurrentPositionAsync({
      enableHighAccuracy: true,
    });
    this.setState({ location  });
      let lat = this.state.location.coords.latitude;
      let long = this.state.location.coords.longitude;

      Geocoder.from(lat,long).then(json => 
        {
        var addressComponent = json.results[0].formatted_address;
        this.setState({addressComponent})

          // Alert.alert(this.state.addressComponent)
      }) 
  }

我正在使用XMLReader,通常使用类似的东西:

import React, {Component} from 'react';
import {View,Text,StyleSheet,FlatList} from 'react-native'

import styles from '../style/styles';

class SetConn extends Component {
    render(){
        return(
            <View>

                     <Text style={styles.addyComp}>{this.props.addressComponent}</Text> 
            </View>
        );
    }
}


export default SetConn;

可以采用其他方法,如果没有简便的方法,我很高兴能找到具有适当名称的 <?xml version="1.0" encoding="UTF-8" ?> <GraphicsConfig> <FX> <Off> <LocalisationName>$QUALITY_OFF;</LocalisationName> <Item> <Feature>LightCones</Feature> <QualitySetting>0</QualitySetting> </Item> <Item> <Feature>LensFlares</Feature> <QualitySetting>0</QualitySetting> </Item> <Item> <Feature>Debris</Feature> <QualitySetting>0</QualitySetting> </Item> <Item> <Feature>ParticleEffects</Feature> <QualitySetting>0</QualitySetting> </Item> <Item> <Feature>Trails</Feature> <QualitySetting>0</QualitySetting> </Item> <Item> <Feature>Beams</Feature> <QualitySetting>0</QualitySetting> </Item> <Item> <Feature>Fog</Feature> <QualitySetting>0</QualitySetting> </Item> </Off> </FX> </GraphicsConfig> 元素,然后仅读取下一个节点,但是以为我会问,因为我一直想提高我的XML编辑知识。

1 个答案:

答案 0 :(得分:0)

下面的代码结合使用XmlReader和XML Linq。我已经发布了很多次此解决方案。在这种情况下,我的首选是不使用XmlReader而是使用XML Linq将结果放入字典中,并同时发布该代码。对于庞大的XML文件,最好始终使用XmlReader以避免内存不足错误。

我在c#和vb.net中都发布了解决方案


Imports System.Xml
Imports System.Xml.Linq
Module Module1

    Const FILENAME As String = "c:\temp\test.xml"
    Sub Main()
        Dim reader As XmlReader = XmlReader.Create(FILENAME)
        Dim items As List(Of Item) = New List(Of Item)()
        While (Not reader.EOF)

            If reader.Name <> "item" Then
                reader.ReadToFollowing("Item")
            End If

            If Not reader.EOF Then

                Dim xItem As XElement = XElement.ReadFrom(reader)
                Dim item As Item = New Item()
                item.feature = xItem.Element("Feature")
                item.setting = xItem.Element("QualitySetting")

                items.Add(item)
            End If
        End While

        'using a dictionary 
        Dim doc As XDocument = XDocument.Load(FILENAME)
        Dim dict As Dictionary(Of String, String) = doc.Descendants("Item") _
            .GroupBy(Function(x) x.Element("Feature").ToString(), Function(y) y.Element("QualitySetting").ToString()) _
            .ToDictionary(Function(x) x.Key, Function(y) y.FirstOrDefault())

    End Sub

End Module
Public Class Item

    Public feature As String
    Public setting As String
End Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReader reader = XmlReader.Create(FILENAME);
            List<Item> items = new List<Item>();
            while (!reader.EOF)
            {
                if(reader.Name != "item")
                {
                    reader.ReadToFollowing("Item");
                }
                if (!reader.EOF)
                {
                    XElement xItem = (XElement)XElement.ReadFrom(reader);
                    Item item = new Item() {
                        feature = (string)xItem.Element("Feature"),
                        setting = (string)xItem.Element("QualitySetting")
                    };

                    items.Add(item);
                }
            }

            //using a dictionary 
            XDocument doc = XDocument.Load(FILENAME);
            Dictionary<string, string> dict = doc.Descendants("Item")
                .GroupBy(x => (string)x.Element("Feature"), y => (string)y.Element("QualitySetting"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
    public class Item
    {
        public string feature { get; set; }
        public string setting { get; set; }
    }
}