无法解析XML字符串。应该很简单

时间:2011-10-21 10:50:44

标签: c# .net xml

我正在尝试使用.net将字符串解析为XElement。我每次都会收到此错误,但无法理解为什么......

“根级别的数据无效。第1行,第1位。”

我试过HTMLEncode但它没有帮助。我也在LinqPad玩过它。

我正在尝试像这样解析字符串(数据是字符串)...

XElement d = XElement.Parse(data);

我想解析的字符串如下所示。有人可以告诉我为什么这不会解析?谢谢。

"<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\" xmlns:media=\"http://search.yahoo.com/mrss/\"><channel><item><title><![CDATA[Download the Bath SU app]]></title><link><![CDATA[http://www.bathstudent.com/news/article/6003/3515/]]></link><pubDate>Thu, 29 Sep 2011 11:59:00 GMT</pubDate><description><![CDATA[Discovering the latest news and events, enjoying exclusive offers, finding your way around campus, checking lecture times... there's an app for that!\r\n\r\nYes, the official University of Bath Students' Union iPhone and Android app is now available free on the Apple App Store. Just search for University of Bath Student Union on the App Store or Android Market and download the app today.\r\n\r\nApp features:\r\n\r\n\r\n\tLatest Students' Union news\r\n\tEvents information\r\n\tExclusive offers and discounts\r\n\tInteractive campus maps\r\n\tCourse and bus timetables\r\n\tStudents' Union contact details\r\n\r\nAnd so much more. It's your essential tool for getting the most out of university life.\r\n]]></description><media:thumbnail url=\"http://m.content.services.bitmix.co.uk/somo/bathuni/listing/Holder@2x.png\" /></item><item><title><![CDATA[Mature Mentoring Scheme]]></title><link><![CDATA[http://www.bathstudent.com/news/article/6003/3531/]]></link><pubDate>Tue, 04 Oct 2011 09:57:00 GMT</pubDate><description><![CDATA[\r\n\r\n\r\n\r\nThe Students’ Union has started a new peer mentoring scheme for mature students. These peer mentors are second and third year mature students who have volunteered to support other mature students.  \r\n \r\nThe mentors are there to provide support and advice on a range of issues such as the experience of being a mature student and sign posting to support services.\r\n \r\nThe scheme is open to all mature undergraduate students and you can have a mature peer mentor even if you already have a departmental mentor.\r\n \r\nIf you would like a mature mentor email - Lisa Benjamin PeerSupport@bath.ac.uk \r\n ]]></description><media:thumbnail url=\"http://m.content.services.bitmix.co.uk/somo/bathuni/listing/Holder@2x.png\" /></item><item><title><![CDATA[Peer Assisted Learning (PAL) pilot kicks off at the University of Bath!]]></title><link><![CDATA[http://www.bathstudent.com/news/article/6003/3532/]]></link><pubDate>Tue, 04 Oct 2011 09:58:00 GMT</pubDate><description><![CDATA[\r\n\r\n\r\n\r\n\r\n\r\nPeer Assisted Learning (PAL) allows more advanced students to give less advanced peers extra help in adjusting to university life and developing the study skills necessary to succeed on their course.  PAL sessions are focus on group discussion and learning and are structured, organised and purposeful while also being informal and friendly. \r\n\r\n\r\n\r\nSome of the benefits of attending PAL sessions are:\r\n\r\n•    It helps new students adjust to higher education\r\n\r\n•    Improves attendees ability to master course concepts by providing students with an opportunity to discuss or practice their subject in a safe place\r\n\r\n•    Develops enhanced study habits\r\n\r\n•    It's free\r\n\r\n\r\n\r\nThis year three new PAL schemes are being piloted with:\r\n\r\no    1st year physic students\r\n\r\no    2nd year Sociology with Human Resource Management students\r\n\r\no    3rd and 4th year Pharmacy students\r\n\r\n\r\n\r\nWant to know more? Go to http://www.bathstudent.com/peer-support/  \r\n]]></description><media:thumbnail url=\"http://m.content.services.bitmix.co.uk/somo/bathuni/listing/Holder@2x.png\" /></item><item><title><![CDATA[New peer mentoring schemes set up across the university]]></title><link><![CDATA[http://www.bathstudent.com/news/article/6003/3533/]]></link><pubDate>Tue, 04 Oct 2011 10:00:00 GMT</pubDate><description><![CDATA[Peer mentoring offers friendly, informal, but confidential support provided for students by students who have had training in listening and helping skills.  Peer Mentors offer practical help and advice to new students, and act as a referral point as appropriate to other support services. \r\n\r\n\r\n\r\nThis year four new schemes have been started across the University in these departments:\r\n\r\no    Politics, Languages &amp; International Studies\r\n\r\no    Social &amp; Policy Sciences (Social Work and Applied Social Studies)\r\n\r\no    Architecture &amp; Civil Engineering\r\n\r\no    Psychology\r\n\r\n\r\n\r\nIf you would like to know more about peer mentoring go to http://www.bathstudent.com/peer-support/mentoring/\r\n\r\n\r\n\r\n \r\n]]></description><media:thumbnail url=\"http://m.content.services.bitmix.co.uk/somo/bathuni/listing/Holder@2x.png\" /></item><item><title><![CDATA[Useful tips from the Police to help keep you and your stuff safe]]></title><link><![CDATA[http://www.bathstudent.com/news/article/6003/3543/]]></link><pubDate>Thu, 06 Oct 2011 09:31:00 GMT</pubDate><description><![CDATA[Check that the property has decent doors &amp; windows with locks that work.  If you’re not happy, speak to your landlord.  Make sure you lock up when you go out and check this has been done.  Don't leave it to someone else.  Most burglaries occur through open windows. Don't leave valuables on show.  Your property can act as a shop window to a thief!\r\n\r\n \r\n\r\nYou may have visitors to your property who you don’t recognise.  Check them out!  Don’t assume they are someone else’s friend.   You’d be surprised how much stuff gets stolen by people just wandering into student properties and helping themselves!  Keep your valuable stuff locked away out of sight.\r\n\r\n\r\n\r\nLaptops are the item of choice for thieves.  If you love yours, look after it.   Mark it with either your parents or the University postcode using a u v marker pen.  Register the details of your laptop, mobile phone and any other lifestyle equipment by visiting www.immobilise.com   All Police forces around the country check this register.  If your stuff is lost or stolen, we may be able to re-unite you with it.\r\n\r\n\r\n\r\nRemember:  \r\n\r\n\r\n\r\nYour laptop\r\n\r\nYour work\r\n\r\nIf it’s stolen,\r\n\r\nYou’re gutted!\r\n\r\n\r\n\r\nSo, what should you be thinking about when you do go out?  Remember, there’s safety in numbers.  When you go out as a group, stick together and look out for each other.  Use taxis or public transport to get around.  Never be tempted into walking up dark alleys or poorly lit pathways.  Don’t flash your cash, or mobile about.  Be discreet with your stuff.  Have a good time but stay in control.  Excessive alcohol consumption is the cause of more of problems than drink spiking. \r\n\r\n\r\n\r\nBath is a safe city with plenty to enjoy.  Let’s keep it that way.  Above all, we wouldn’t want you to become one of the few victims that suffers a crime.  \r\n\r\n \r\n\r\n \r\n]]></description><media:thumbnail url=\"http://m.content.services.bitmix.co.uk/somo/bathuni/listing/Holder@2x.png\" /></item><item><title><![CDATA[Fireworks tickets on sale now!]]></title><link><![CDATA[http://www.bathstudent.com/rag/events/fireworks/]]></link><pubDate>Fri, 07 Oct 2011 16:30:00 GMT</pubDate><description><![CDATA[\r\n\r\n\r\n\r\n\r\n]]></description><media:thumbnail url=\"http://m.content.services.bitmix.co.uk/somo/bathuni/listing/Holder@2x.png\" /></item><item><title><![CDATA[Do you want to help embed an environmental culture at the Uni?]]></title><link><![CDATA[http://www.bathstudent.com/news/article/6003/3562/]]></link><pubDate>Tue, 11 Oct 2011 09:50:00 GMT</pubDate><description><![CDATA[\r\n\r\nSTUDENTS…\r\n\r\nWant to be a part of embedding an environmental culture at our Uni! –come along on\r\n\r\n\r\n\r\nFRIDAY 11 NOVEMBER 1.15 – 2.05PM,  LUNCH PROVIDED\r\n\r\n\r\n\r\nOpportunities you’ll get in return:\r\n\r\n\timproving environmental practices at departmental level,\r\n\tintroducing ideas to reduce our carbon footprint,\r\n\tlearning how to achieve change on campus,\r\n\tdeveloping leadership and team skills,\r\n\tbeing involved in Global Future 2012,\r\n\tworking alongside academic and support staff,\r\n\tenhancing your CV.\r\n\r\n\r\n\r\nContact Sal by 3rd Nov to book a place (s.lampkin@bath.ac.uk/x5741), venue TBC\r\n\r\n \r\n \r\n]]></description><media:thumbnail url=\"http://m.content.services.bitmix.co.uk/somo/bathuni/listing/Holder@2x.png\" /></item><item><title><![CDATA[Would you like to share your views on the SU?]]></title><link><![CDATA[http://www.bathstudent.com/news/article/6003/3564/]]></link><pubDate>Wed, 12 Oct 2011 15:22:00 GMT</pubDate><description><![CDATA[\r\n\r\n\r\n\r\nWould you like to sit on an important panel and share your views on how well the Students’ Union is doing?\r\n\r\nWe are looking for three students to sit on the Students’ Union’s newly established Review Panel.  The Review Panel was developed last year to act as a critical friend to the Union and to the Sabbatical Trustees to give advice and help us better achieve our mission.  \r\n\r\nThe Panel is made up of the chairs of the nine Executive Committees of the Students’ Union as well as three students appointed by the Panel. The dates for the Panel’s meetings are: 9th December (14.00 – 17.00) and  27th April from (14.00 – 17.00).\r\n\r\nYou will be a reliable student, interested in the value of a Students’ Union and not afraid to share your views. This is a great opportunity to be a part of a very important group in the Students’ Union, to help influence its decision makers and to improve your CV.\r\n\r\nIf you want further information, you can talk to any of the Sabbatical Officers or Alison Fleet, who can also provide the full remit of the Panel on request: A.J.Fleet@bath.ac.uk (1East 3.10a)\r\n\r\nPlease send a letter of application describing why you should be selected by email to A.J.Fleet@bath.ac.uk by Monday 24th October 2011.  \r\n\r\nApplications will then be considered by the Panel on Friday 4th November and you will be notified after that as to whether you are successful or not.\r\n]]></description><media:thumbnail url=\"http://m.content.services.bitmix.co.uk/somo/bathuni/listing/Holder@2x.png\" /></item><item><title><![CDATA[Students urged to lock their doors after spate of burglaries]]></title><link><![CDATA[http://www.thisisbath.co.uk/Students-urged-lock-doors-spate-burglaries/story-13546749-detail/story.html]]></link><pubDate>Fri, 14 Oct 2011 10:47:00 GMT</pubDate><description><![CDATA[]]></description><media:thumbnail url=\"http://m.content.services.bitmix.co.uk/somo/bathuni/listing/Holder@2x.png\" /></item><item><title><![CDATA[Take part in our Freshers' Week Survey online now!]]></title><link><![CDATA[http://www.bathstudent.com/news/article/6003/3568/]]></link><pubDate>Fri, 14 Oct 2011 16:23:00 GMT</pubDate><description><![CDATA[ \r\n\r\nThe Students' Union wants to know what you thought of the whole  Freshers' Week experience so that it can be improved on for future  years. It should only take between 5-10 minutes. Undergrads could be in with a chance of winning a £100 food and drinks voucher for the Plug or Postgrads could win £50 worth of amazon vouchers!\r\n\r\nTake the survey now! \r\n\r\nFreshers' Undergraduate \r\n\r\nhttps://survey.bathstudent.com/freshersweek2011\r\n\r\nFreshers' Postgraduate \r\n\r\nhttps://survey.bathstudent.com/pgfreshersweek2011]]></description><media:thumbnail url=\"http://m.content.services.bitmix.co.uk/somo/bathuni/listing/Holder@2x.png\" /></item><item><title><![CDATA[Keep your bike safe on campus]]></title><link><![CDATA[http://www.bathstudent.com/news/article/6003/3559/]]></link><pubDate>Mon, 10 Oct 2011 14:36:00 GMT</pubDate><description><![CDATA[\r\n\r\nThe Security Department hires out cycle shackles for the whole academic year against a returnable deposit of £15 if they are given back in working order.  For the six years the scheme has been in operation, no bikes secured with such shackles have been stolen.  Thieves are focusing their attention on stealing bikes secured by curly wire locks that they can easily cut. \r\n\r\n\r\n\r\nFor further information see the web page at:http://www.bath.ac.uk/security/cycling/bike-security.shtml\" \r\n]]></description><media:thumbnail url=\"http://m.content.services.bitmix.co.uk/somo/bathuni/listing/Holder@2x.png\" /></item><item><title><![CDATA[Cross-Campus, Faculty Reps and Executive Committee elections - nominations open now]]></title><link><![CDATA[http://www.bathstudent.com/news/article/6003/3577/]]></link><pubDate>Mon, 17 Oct 2011 12:26:00 GMT</pubDate><description><![CDATA[It's election time again. Nominations are now open for the following elections.\r\n\r\nClick on the relevant post below for details of how to nominate yourself:\r\n\r\nStudents' Union cross-campus elections\r\n\r\n\tCSSU (Council, Senate, Students' Union Committee) \r\n\tNUS Delegates\r\n\r\nAcademic elections \r\n\r\n\tFaculty Reps\r\n\tPostgraduate Senate Reps\r\n\tSecond-round Academic Reps\r\n\r\nDiversity and Support Executive elections\r\n\r\n\tRace Equality Rep \r\n\tPublicity Officer\r\n\tTreasurer\r\n\r\nPostgraduate Students Association (PGA) elections\r\n\r\n\t  Click here for all posts\r\n\r\nInternational Students Association (ISA) elections \r\n\r\n\tClick here for all posts\r\n\r\nSocieties Executive election\r\n\r\n\tFaith and Cultural Officer\r\n\r\nTo stand in the elections, please go to the relevant election and upload your photograph and manifesto. Nominations will be open until midnight on October 23 for the Faculty Rep and Postgraduate Senate Rep elections and noon on October 21 for all other elections.\r\n\r\nYou can also find out more details about  each election, please see www.bathstudent.com/democracy or the relevant organisation's web page.\r\n\r\n \r\n\r\n \r\n]]></description><media:thumbnail url=\"http://m.content.services.bitmix.co.uk/somo/bathuni/listing/Holder@2x.png\" /></item><item><title><![CDATA[Student shop 2011: could you come out on top?]]></title><link><![CDATA[http://www.bath.ac.uk/news/2011/10/17/student-shop-11/]]></link><pubDate>Mon, 17 Oct 2011 14:20:00 GMT</pubDate><description><![CDATA[]]></description><media:thumbnail url=\"http://m.content.services.bitmix.co.uk/somo/bathuni/listing/Holder@2x.png\" /></item><item><title><![CDATA[Appointments with Advice and Representation Centre]]></title><link><![CDATA[http://www.bathstudent.com/news/article/15267/3471/]]></link><pubDate>Thu, 20 Oct 2011 11:58:00 GMT</pubDate><description><![CDATA[]]></description><media:thumbnail url=\"http://m.content.services.bitmix.co.uk/somo/bathuni/listing/Holder@2x.png\" /></item><item><title><![CDATA[Get your extra curricular activities credited]]></title><link><![CDATA[http://www.bathstudent.com/bathaward/studentsupport/]]></link><pubDate>Thu, 20 Oct 2011 13:44:00 GMT</pubDate><description><![CDATA[]]></description><media:thumbnail url=\"http://m.content.services.bitmix.co.uk/somo/bathuni/listing/Holder@2x.png\" /></item><item><title><![CDATA[NUS Extra]]></title><link><![CDATA[http://cards.nus.org.uk/buy/default.aspx]]></link><pubDate>Thu, 04 Aug 2011 12:44:00 GMT</pubDate><description><![CDATA[]]></description><media:thumbnail url=\"http://www.bathstudent.com/asset/News/6003/EXTRA-BETTER-copy.jpg?thumbnail_width=200&amp;thumbnail_height=160&amp;resize_type=Force\" /></item><item><title><![CDATA[LIKE us on Facebook]]></title><link><![CDATA[http://www.facebook.com/BathSU]]></link><pubDate>Mon, 03 Oct 2011 12:13:00 GMT</pubDate><description><![CDATA[]]></description><media:thumbnail url=\"http://www.bathstudent.com/asset/News/6003/FACEBOOK-copy.jpg?thumbnail_width=200&amp;thumbnail_height=160&amp;resize_type=Force\" /></item><item><title><![CDATA[Freshers' Week Survey]]></title><link><![CDATA[http://www.bathstudent.com/news/article/busu/3568/]]></link><pubDate>Mon, 17 Oct 2011 09:56:00 GMT</pubDate><description><![CDATA[]]></description><media:thumbnail url=\"http://www.bathstudent.com/asset/News/6003/survey-copy.jpg?thumbnail_width=200&amp;thumbnail_height=160&amp;resize_type=Force\" /></item><item><title><![CDATA[Elections nominations now open]]></title><link><![CDATA[http://www.bathstudent.com/democracy/]]></link><pubDate>Wed, 19 Oct 2011 16:28:00 GMT</pubDate><description><![CDATA[]]></description><media:thumbnail url=\"http://www.bathstudent.com/asset/News/6003/Vote.jpg?thumbnail_width=200&amp;thumbnail_height=160&amp;resize_type=Force\" /></item></channel></rss>"

3 个答案:

答案 0 :(得分:5)

我已经成功了。这是因为在运行时字符串中出现了不可打印的unicode字符。当我正在应对并粘贴到这篇文章时,这种情况正在消失。 如果我在尝试解析之前通过此方法运行字符串一切正常。

    public string getRidOfUnprintablesAndUnicode(string inpString)
    {
        string outputs = String.Empty;
        for (int jj = 0; jj < inpString.Length; jj++)
        {
            char ch = inpString[jj];
            if (((int)(byte)ch) >= 32 & ((int)(byte)ch) <= 128)
            {
                outputs += ch;
            }
        }
        return outputs;
    }   

答案 1 :(得分:2)

“根级别的数据无效。第1行,第1位。”通常意味着xml具有前导空格。它在这里解析得很好,所以请确认实际数据中没有前导空格(特别是换行等)(也许你没有在问题中显示)。具体来说,以下工作正常:

string data = ... // string literal from the question
XElement d = XElement.Parse(data);

答案 2 :(得分:2)

我遇到了同样的问题,试图解析一个漂亮而干净的RSS源,看起来像有效的XML(here,如果你想知道)。然后我注意到XElement.Load(new MemoryStream(dataBytes))正常工作,而当我首先将字节转换为UTF8字符串时问题出现了。

这似乎完全无法解释,因为XML是Unicode是XML,那么为什么有效的非ASCII字符会抛出任何东西呢?看看字节,......问题立即显露出来:

物料清单抬头丑陋!

Byte Order Marker是煽动者。

如果你也开始使用字节,但是首先需要使用字符串,这是最有效的方法:

bool bom = (data[0] == 239 && data[1] == 187 && data[2] == 191); // Detect BOM, 239, 187, 191
int substract = bom ? 3 : 0;
string feedStr = Encoding.UTF8.GetString(data, bom ? substract : 0, data.Length - substract);
// do something
XElement e = XElement.Parse(feedStr); // works now