简体   繁体   English

使用C#和XDocument进行XML解析-XmlException:预期为“文件”

[英]XML Parsing with C# and XDocument - XmlException: 'file' is expected

I've got this error: 我有这个错误:

XmlException: 'chipdb' is expected file:///C:/Users/Mkh/Documents/MMBN3D/Assets/Resources/ChipDatabase.xml Line 12, position 8. XmlException:预期为“ chipdb”文件:/// C:/Users/Mkh/Documents/MMBN3D/Assets/Resources/ChipDatabase.xml第12行,位置8。

When trying to parse the following file: 尝试解析以下文件时:

<?xml version="1.0" encoding="ISO-8859-1"?>
<chipdb>
    <chip>
        <name> Cannon1 </name>
        <dmg> 30 </dmg>
        <smallicon> </smallicon>
        <bigicon> </bigicon>
        <type> Straight </type>
        <element> None </element>
        <description> One of the most basic chips. </description>
    </chip>
</chipbd>

I only need to find the correct chip, and then use this data to initiate a chip object that will be used elsewhere. 我只需要找到正确的芯片,然后使用此数据来启动将在其他地方使用的芯片对象。 To do this I am using XDocument, and had some trouble with it because I never worked with XML. 为此,我使用XDocument,但由于从未使用过XML,因此遇到了一些麻烦。 The code I made is the following: 我编写的代码如下:

    using UnityEngine;

using System.Xml.Linq;
using System.Collections;

public class XMLAttackParser : MonoBehaviour
{
    XDocument doc;

    // Use this for initialization
    void Start ()
    {
        doc = new XDocument();
        doc = XDocument.Load( "Assets/Resources/ChipDatabase.xml" );
    }

    // Update is called once per frame
    void Update ()
    {

    }

    bool searchChip ( string name )
    {
        var chips = doc.Descendants( "chip" );

        foreach (var item in chips)
        {
            if( item.Element( "name" ).ToString() == name )
            {
                Debug.Log( "Man" );
                return true;
            }
        }

        return true;
    }
}

Can someone help me out? 有人可以帮我吗? Thanks. 谢谢。

You mistyped chipdb for the closing tag at the end of the document: chipbd . 您在文档末尾将chipdb为结尾标签: chipbd

Someone had pointed out (but removed his message) that you also have a mistake on: item.Element( "name" ).ToString() which should be: 有人指出(但删除了他的消息),您在以下item.Element( "name" ).ToString()上也犯了一个错误: item.Element( "name" ).ToString()应该是:

item.Element( "name" ).Value

or 要么

(string)item.Element("name")

Indeed, item.Element( "name" ).ToString() will return: <name> cannon1 </name> 实际上, item.Element( "name" ).ToString() . item.Element( "name" ).ToString()将返回: <name> cannon1 </name>

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

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