【发布时间】:2021-07-22 20:21:55
【问题描述】:
这是 XML
<GeoLoc>
<Location>
<AddrLn1>384-393 COMMERCIAL ROAD</AddrLn1>
<Town>LONDON</Town>
<PostCode>E1 0LR</PostCode>
<Country>ENGLAND</Country>
<UPRN>100080712803</UPRN>
</Location>
</GeoLoc>
这是我的子程序
private GeoLoc GetGeoLoc(XmlReader reader)
{
GeoLoc _geoloc = new GeoLoc();
_geoloc.Location = new Location();
if (reader.ReadToDescendant("Location"))
{
if (reader.ReadToFollowing("AddrLn1"))
{
_geoloc.Location.AddrLn1 = reader.ReadElementContentAsString();
}
if (reader.ReadToFollowing("AddrLn2"))
{
_geoloc.Location.AddrLn2 = reader.ReadElementContentAsString();
}
if (reader.ReadToFollowing("AddrLn3"))
{
_geoloc.Location.AddrLn3 = reader.ReadElementContentAsString();
}
if (reader.ReadToFollowing("Town"))
{
_geoloc.Location.Town = reader.ReadElementContentAsString();
}
if (reader.ReadToFollowing("County"))
{
_geoloc.Location.County = reader.ReadElementContentAsString();
}
if (reader.ReadToFollowing("PostCode"))
{
_geoloc.Location.PostCode = reader.ReadElementContentAsString();
}
if (reader.ReadToFollowing("Country"))
{
_geoloc.Location.Country = reader.ReadElementContentAsString();
}
if (reader.ReadToFollowing("UPRN"))
{
_geoloc.Location.UPRN = reader.ReadElementContentAsString();
}
}
return _geoloc;
}
问题是它只读取 AddrLn1,然后读取器变为无。我尝试了 ReadSubTree() 但结果相同。请注意,某些 Geoloc 示例中可能缺少某些标签,AddrLn2 或 AddrLn3 可能存在。
【问题讨论】:
-
问题是没有地址行 2,所以您将在文件末尾找不到任何东西。您可以使用以下内容:XmlReader child = reader.ReadSubtree();
-
谢谢@jdweng,我应该在哪里添加这个?以及如何检查以跳过丢失的元素?
-
如果找不到项目,阅读器将处于 EOF。或者你可以移动到下一个元素。
-
您需要两个阅读器,因此当您没有找到某个项目时,您仍然在当前位置。 XmlReader child = reader.ReadSubtree(); if (child.ReadToFollowing("Country")) { reader = child; _geoloc.Location.County = reader.ReadElementContentAsString();}
-
所以我试过了,但是当 inner.ReadElementContentAsString();读取器和子读取器都被执行成为“空白,值=\”\“”