简体   繁体   中英

I can not load a xml file in xamarin android

<?xml version='1.0' encoding='ISO-8859-1' standalone='yes'?>
<Collection>
<Book Id='1' ISBN='1-100000ABC-200'>
<Title>Principle of Relativity</Title>
<!-- Famous physicist -->      
<Author>Albert Einstein</Author>
<Genre>Physics</Genre>
</Book>
<Book Id='2' ISBN='1-100000ABC-300'>
  <!-- Also came as a TV serial -->
  <Title>Cosmos</Title>
  <Author>Carl Sagan</Author>
  <Genre>Cosmology</Genre>
  </Book>
<!-- Add additional books here -->
</Collection>

i place my xml file in Resources/drawable and build action in set to Android Resources when i start the application exception occur System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.i am not sure what this exception means please help

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Linq;
using System.Text;
using System.Xml.XPath;
using Android.Content.Res;
using System.IO;
namespace App16
{
[Activity(Label = "App16", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    int count = 1;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
     string content;
        AssetManager assets = this.Assets;
        using (StreamReader sr = new StreamReader(assets.Open("Q317664.xml")))
       {
           content = sr.ReadToEnd();
       }
 XmlDocument doc = new XmlDocument();
        doc.LoadXml("content");
}
}
}

LoadXml method takes the XML string as parameter. You are passing the string "content" to the method, which is causing the issue. As per your logic it should be

 doc.LoadXml(content); //without ""

But I also suspect if the XML is correctly loaded with this code. If this doesn't work, you may check the value of the variable content, if it has the XML string parsed into it. There is documentation by Xamarin on how to load files as Embedded Resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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