Main Content

readstruct

Create structure from file

    Description

    example

    S= readstruct(filename)creates a structure by reading structured data from a file. The input file must contain a well-formed XML structure.

    readstructautomatically detects the datatypes of the contents in the input file.

    example

    S= readstruct(filename,Name,Value)creates a structure from a file with additional options specified by one or more name-value pair arguments. For example, you can read the contents of the input file as XML when the file extension infilenameis not.xmlby callingS = readstruct(filename,'FileType','xml').

    Examples

    collapse all

    Read an XML file as a structure, create variables from the structure, and query its contents.

    The filemusic.xmlhas the following structure.

    music.png

    Readmusic.xmlinto MATLAB as a structureS. This structure contains one parent nodeMusicalEnsemblethat has two sibling nodes,EnsembleandMusicians.

    S = readstruct("music.xml")
    S =struct with fields:Ensemble: [1x1 struct] Musicians: [1x1 struct]

    Create a variablebandfrom the first sibling node.bandhas three fields, one of which is a structure namedInstrumentation.

    band = S.Ensemble
    band =struct with fields:Music: "Jazz" BandName: "Kool Katz" Instrumentation: [1x1 struct]

    查询Instrumentationinbandto view its contents.

    band.Instrumentation
    ans =struct with fields:Instrument: [1x4 struct]

    Create a variablemusiciansfrom the second sibling node.musicianshas one field calledName, which contains five structures.

    musicians = S.Musicians
    musicians =struct with fields:Name: [1x5 struct]

    Create a structure from an XML file that does not contain uniformly-structured data, then show its contents.

    If a sibling node contains fields that other sibling nodes do not have,readstructreturnsmissingfor the fields that are not found in other nodes. For example, in the filemusic.xml, the secondInstrumentnode contains a non-empty fieldpianotype. Since the otherInstrumentnodes do not have a value specified forpianotype,readstructreturnsmissingforpianotypeunder thoseInstrumentnodes.

    music.png

    Read the XML filemusic.xmlto a structureS.

    S = readstruct("music.xml")
    S =struct with fields:Ensemble: [1x1 struct] Musicians: [1x1 struct]

    查询the Instrument structure in S to view its contents.

    S.Ensemble.Instrumentation.Instrument
    ans=1×4 struct array with fields:typeAttribute Text pianotype drumkit basstype

    Read a text file as a structure.

    The filemusic.txthas the following structure.

    music.png

    Read the text filemusic.txtinto MATLAB® as a structureS. Specify'FileType'as'xml'to read the contents of the input as an XML file.

    S = readstruct("music.txt","FileType","xml")
    S =struct with fields:Ensemble: [1x1 struct] Musicians: [1x1 struct]

    Create a structure from a specific element node in the input file by using the'StructNodeName'name-value pair.

    Read theInstrumentationnode from the XML filemusic.xml.

    S = readstruct("music.xml","StructNodeName","Instrumentation")
    S =struct with fields:Instrument: [1x4 struct]

    Specify the precise XML element node under which to start reading the structure in the input file.

    Read the fifthNameXML文件中的元素music.xml. Specify the full XPath expression of the element node as the value of'StructSelector'.

    S = readstruct("music.xml","StructSelector","/MusicalEnsemble/Musicians/Name[5]")
    S =struct with fields:roleAttribute: "bassist" Text: "John"

    Register a custom XML namespace prefix to the existing namespace URL in the input file using theRegisteredNamespacesname-value argument.

    To read the secondStreetelement node as a structure, specify the value of'StructSelector'as'//Student[2]/Address/myPrefix:Street'and the value ofRegisteredNamespacesas["myPrefix","//www.tianjin-qmedu.com"].

    S = readstruct("students.xml","RegisteredNamespaces",["myPrefix","//www.tianjin-qmedu.com"],..."StructSelector",'//Student[2]/Address/myPrefix:Street')
    S =struct with fields:xmlnsAttribute: "//www.tianjin-qmedu.com" Text: "4641 Pearl Street"

    Input Arguments

    collapse all

    Name of the file to read, specified as a character vector or a string scalar.

    Depending on the location of your file,filenamecan take one of these forms.

    Location

    Form

    Current folder or folder on the MATLAB®path

    指定文件的名称filename.

    Example:'myFile.xml'

    File in a folder

    If the file is not in the current folder or in a folder on the MATLAB path, then specify the full or relative path name infilename.

    Example:“C: \ myFolder \ myFile.xml'

    Example:'dataDir\myFile.xml'

    Internet URL

    If the file is specified as an internet uniform resource locator (URL), thenfilenamemust contain the protocol type'http://'or'https://'.

    Example:'http://hostname/path_to_file/my_data.xml'

    Remote Location

    If the file is stored at a remote location, thenfilenamemust contain the full path of the file specified with the form:

    scheme_name://path_to_file/my_file.ext

    Based on the remote location,scheme_namecan be one of the values in this table.

    Remote Location scheme_name
    Amazon S3™ s3
    Windows Azure®Blob Storage wasb,wasbs
    HDFS™ hdfs

    For more information, seeWork with Remote Data.

    Example:'s3://bucketname/path_to_file/my_setup.xml'

    Name-Value Arguments

    Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN, whereNameis the argument name andValueis the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

    Before R2021a, use commas to separate each name and value, and encloseNamein quotes.

    Example:'ImportAttributes',truespecifies to import the attributes associated with element nodes as fields of the output structure.

    Type of file, specified as the comma-separated pair consisting of'FileType'and one of these values:

    • 'auto'— Automatically detect the file format of the input file from the extension specified infilename.

    • 'xml'— Read the contents of the input file as XML.

    If the file extension infilenameis not.xml, you can specify the value of'FileType'as'xml'to read the contents of the input file as XML.

    Example:'FileType','xml'

    语言环境对阅读的日期, specified as the comma-separated pair consisting of'DateLocale'and a character vector or a string scalar of the formxx_YY, where:

    • YYis an uppercase ISO 3166-1 alpha-2 code indicating a country.

    • xxis a lowercase ISO 639-1 two-letter code indicating a language.

    This table lists some common values for the locale.

    Locale Language Country
    'de_DE' German Germany
    'en_GB' English United Kingdom
    'en_US' English United States
    'es_ES' Spanish Spain
    'fr_FR' French France
    'it_IT' Italian Italy
    'ja_JP' Japanese Japan
    'ko_KR' Korean Korea
    'nl_NL' Dutch Netherlands
    'zh_CN' Chinese (simplified) China

    Example:'DateLocale','ja_JP'

    Starting XML element, specified as the comma-separated pair consisting of'StructNodeName'and either a character vector or string scalarreadstructreads the structure in the input file, starting with the specified XML element. If you do not specifyStructNodeName, thenreadstructreads the structure starting at the root of the XML file.

    readstructmatches the first node in the XML document whose name matches the value specified inStructNodeName.

    Example:'StructNodeName','RootName'

    Starting XML Path, specified as the comma-separated pair consisting of'StructSelector'and a character vector or string scalarreadstructreads the structure in the input file starting at the element at the specified path. The value of'StructSelctor'must be a valid XPath version 1.0 expression.

    Import attributes, specified as the comma-separated pair consisting of'ImportAttributes'and either1(true) or0(false). If you specify the value asfalse, thenreadstructwill not import the XML attributes in the input file as fields in the output structure.

    Example:'ImportAttributes',false

    Attribute suffix, specified as the comma-separated pair consisting of'AttributeSuffix'and either a character vector or string scalar.readstructappends this suffix to all field names of the output structure that correspond to attributes in the input XML file. If you do not specify'AttributeSuffix', thenreadstructdefaults to appending the suffix'Attribute'to all field names corresponding to attributes in the input XML file.

    Example:'AttributeSuffix','_att'

    Set of registered XML namespace prefixes, specified asRegisteredNamespacesand an array of prefixes. The reading function uses these prefixes when evaluating XPath expressions on an XML file. Specify the namespace prefixes and their associated URLs as an Nx2 string array.RegisteredNamespacescan be used when you also evaluate an XPath expression specified by a selector name-value argument, such asStructSelectorforreadstruct, orVariableSelectorsforreadtableandreadtimetable.

    By default, the reading function automatically detects namespace prefixes to register for use in XPath evaluation, but you can also register new namespace prefixes using theRegisteredNamespacesname-value argument. You might register a new namespace prefix when an XML node has a namespace URL, but no declared namespace prefix in the XML file.

    For example, evaluate an XPath expression on an XML file calledexample.xmlthat does not contain a namespace prefix. Specify'RegisteredNamespaces'as["myprefix", "//www.tianjin-qmedu.com"]to assign the prefixmyprefixto the URL//www.tianjin-qmedu.com.

    S = readstruct("example.xml",StructSelector="/myprefix:Data",... RegisteredNamespaces=["myprefix", "//www.tianjin-qmedu.com"])

    Example:'RegisteredNamespaces',["myprefix", "//www.tianjin-qmedu.com"]

    HTTPorHTTPSrequest options, specified as aweboptionsobject. Theweboptionsobject determines how to import data when the specifiedfilenameis an internet URL containing the protocol type"http://"or"https://".

    Output Arguments

    collapse all

    Output structure. A structure is a data type that groups related data using data containers called fields. Each field can contain any type of data. Access data in a structure using dot notation of the formstructName.fieldName. For more information on structures, seestruct.

    Tips

    • Use XPath selectors to specify which elements of the XML input document to import. This table provides the XPath syntaxes that are supported by the XPath selector name-value argumentStructSelector.

      Selection Operation Syntax Example Result
      Select the node whose name matches the node you want to select, regardless of its location in the document. 公关efix the name with two forward slashes (//).
      数据= readstruct ("music.xml",StructSelector="//Ensemble")
      data = struct with fields: Music: "Jazz" BandName: "Kool Katz" Instrumentation: [1×1 struct]
      Select a specific node in a set of nodes. 公关ovide the index of the node you want to select in square brackets ([]).
      数据= readstruct ("music.xml",...StructSelector=..."//Ensemble/Instrumentation/Instrument[3]")
      data = struct with fields: typeAttribute: "percussion" Text: "Drums" drumkit: ["Bass drum" "Floor tom" "Snare drum"... "Hi-hat" "Ride cymbal"]
      Specify precedence of operations. Add parentheses around the expression you want to evaluate first.
      数据= readstruct ("students.xml",...StructSelector="//Student/Name[4]")
      Error using readstruct No node with the selector '//Student/Name[4]' could be... found in the file 'students.xml'. 'StructSelector' must... refer to a valid node.
      数据= readstruct ("students.xml",...StructSelector="(//Student/Name)[4]")
      data = struct with fields: FirstNameAttribute: "Salim" LastNameAttribute: "Copeland"

    Version History

    Introduced in R2020b

    See Also