解析XML字符串出现问题。应该很简单。

4
我正在尝试使用.net将字符串解析为XElement。每次都会出现以下错误,我无法弄清原因...
“根级别的数据无效。第1行,第1个位置。”
我已经尝试过对其进行HTMLEncode,但没有帮助。我还在LinqPad中进行了一些尝试。
我正在尝试像这样解析字符串(其中data是一个字符串)...
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>"

你的 XML 文件太大了!也许你可以将其缩小为一个更小的示例?只保留一些示例元素即可! - gideon
最外层的“引号”实际上是字符串的一部分吗?它们不应该在那里。属性值周围的引号不应该被转义。 - Max
对不起,它们是字符串定义的一部分,而不是XML本身。 - Ben Cameron
@Max 因为那是一个 C# 编码的字符串字面量,所以它们应该被保留。 - Marc Gravell
1
这里它正常工作。 - xanatos
显示剩余2条评论
3个回答

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;
    }   

3
在每次循环中使用StringBuilder而不是连接字符。 - Mihail Shishkov

4
我在尝试解析一个看起来美观干净的RSS源时遇到了同样的问题,它看起来像是一个有效的XML(这里如果您想知道)。然后我注意到使用XElement.Load(new MemoryStream(dataBytes))可以正常工作,但当我首先将字节转换为UTF8字符串时出现了问题。
这似乎完全无法解释,因为XML是Unicode,所以为什么有效的非ASCII字符会引起任何问题呢?嗯,在查看字节时......问题立即被揭示: BOM露出了丑陋的头! 字节顺序标记是罪魁祸首。
如果您也开始使用字节,但需要首先使用字符串进行操作,则这是最有效的方法:
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

2
“根级别的数据无效。第1行,第1个位置。”通常表示 XML 文件具有前导空格。这里可以成功解析,因此请验证实际数据中没有前导空格(特别是换行符等),可能您在问题中没有显示。具体来说,以下内容可以正常工作:
string data = ... // string literal from the question
XElement d = XElement.Parse(data);

好的想法,但我不认为那就是问题所在。我仍然在执行这个操作时遇到了一个错误... XElement d = XElement.Parse(data, LoadOptions.None); - Ben Cameron
这里也可以正常工作。问题在于你提供给我们的 XML 不是你尝试解析的 XML。 - Grokys
谢谢大家,我已经在一个示例应用程序中使其工作了,所以肯定是与实际的真实应用程序以及如何处理字符串有关。我会继续努力解决它。谢谢。 - Ben Cameron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接