解析xml字符串并摆脱根元素错误

时间:2017-01-17 15:21:46

标签: c# xml xml-parsing umbraco

我将此字符串结构化为XML:

<damp fullmedia="">
  <mediaitem>
    <img id="1119" version="29a5623f-d41c-4418-97b7-3cea8579ffd8" parentid="1052" level="2" writerid="0" nodetype="1032" template="0" sortorder="2" createdate="2016-11-30T10:09:40" updatedate="2016-11-30T10:09:40" nodename="2016-11-25_1251411957-277" urlname="2016-11-25_1251411957-277" writername="admin" nodetypealias="Image" path="-1,1052,1119">
      <umbracofile>/media/1013/2016-11-25_1251411957-277.jpg</umbracofile>
      <umbracowidth>2598</umbracowidth>
      <umbracoheight>1732</umbracoheight>
      <umbracobytes>350613</umbracobytes>
      <umbracoextension>jpg</umbracoextension>    
    </img>
  </mediaitem>
</damp>

我想提取属性“umbracofile”的值,所以我这样做了:

var stringAsXml = "<damp fullmedia="">....";
var xmlDoc = new XmlDocument();
var imageUrl = xmlDoc.SelectSingleNode("//mediaItem/img/umbracoFile").InnerText;

代码工作正常,但我有错误“根元素丢失”。由于我只想解析并提取节点值,我该如何摆脱这个错误呢?

1 个答案:

答案 0 :(得分:1)

  

代码工作正常,但我有错误&#34; Root元素缺失&#34;。

那么我觉得代码没那么好用吗?这应该有效:

$day // 2017-01-01
$YearWeek // I get 201752 instead of 201652

还有这个(如果你有几个var stringAsXml = "<damp fullmedia=\"\"><mediaitem><img id=\"1119\" version=\"29a5623f-d41c-4418-97b7-3cea8579ffd8\" parentid=\"1052\" level=\"2\" writerid=\"0\" nodetype=\"1032\" template=\"0\" sortorder=\"2\" createdate=\"2016-11-30T10:09:40\" updatedate=\"2016-11-30T10:09:40\" nodename=\"2016-11-25_1251411957-277\" urlname=\"2016-11-25_1251411957-277\" writername=\"admin\" nodetypealias=\"Image\" path=\"-1,1052,1119\"><umbracofile>/media/1013/2016-11-25_1251411957-277.jpg</umbracofile><umbracowidth>2598</umbracowidth><umbracoheight>1732</umbracoheight><umbracobytes>350613</umbracobytes><umbracoextension>jpg</umbracoextension></img></mediaitem></damp>"; var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(stringAsXml); var imageUrl = xmlDoc.SelectSingleNode("damp/mediaitem/img/umbracofile").InnerText; 个节点,并且想要选择第一个节点):

<umbracofile>