更新时间:2023-11-24 15:24:10
我会这样做:
XPathDocument doc = new XPathDocument(" input.xml");
XPathNavigator nav = doc.CreateNavigator();
XmlNamespaceManager mgr = new XmlNamespaceManager(nav.NameTable);
mgr.AddNamespace(" g"," http://base.google.com/ns/1.0");
foreach(doc.CreateNavigator()中的XPathNavigator项。选择(&rss / channel / item"))
{
foreach(项目中的XPathNavigator链接。选择(") ; g:image_link",mgr))
{
Console.WriteLine(link.Value);
}
}
I am using XPathDocument to read xml. XML Document format is given below. You can see that there are two similar elements with name of <g:image_link> ...how can i read identical elements?my current code only gets first image_link not second one. snippet of my program along with xml is given below
/////////////////////Main code/////////////////////////////
static private XPathDocument _doc;
static private XPathNavigator _nav;
static private XPathNavigator nav2;
static private XPathNodeIterator iterator;
static private RssXmlReader rssXmlReader;
_doc = new XPathDocument(_rssReaderUri);
_nav = _doc.CreateNavigator();
XPathExpression expr;
expr = _nav.Compile("/rss/channel/item");
iterator = _nav.Select(expr);
try
{
while (iterator.MoveNext())
{
nav2 = iterator.Current.Clone();
string gns = nav2.LookupNamespace("g");
string cns = nav2.LookupNamespace("c");
RssItemData temp = new RssItemData();
temp.Image_Link = "image_link@" + gns;
}
////////// RssItemData class snippet.//////////////////
private string _imageLink;
public string Image_Link
{
get { return _imageLink; }
set { _imageLink = RssXmlReader.getItemAttribute(value); }
}
//////////////////////getItemAttribute//////////////////////
internal static string getItemAttribute(string attributeName)
{
bool bChildFound = false;
string[] str = attributeName.Split('@');
if (str.Length > 1)
{
bChildFound = nav2.MoveToChild(str[0], str[1]);
}
else
{
bChildFound = nav2.MoveToChild(attributeName, "");
}
if (bChildFound)
{
string attribVal = nav2.Value;
nav2.MoveToParent();
return attribVal;
}
return "";
}
///////////XML///////////////////////////
- <rss version="2.0" xmlns:g="http://base.google.com/ns/1.0" xmlns:c="http://base.google.com/cns/1.0">
- <channel>
<title>Website RSS</title>
<description>Rss from testing company</description>
- <item>
<g:image_link>http://testingcompany/Photos/793_1623.jpg</g:image_link>
<g:image_link>http://testingcompany/Photos/793_1622.jpg</g:image_link>
</item>
</channel>
</rss>
I would simply do it like this:
XPathDocument doc = new XPathDocument("input.xml"); XPathNavigator nav = doc.CreateNavigator(); XmlNamespaceManager mgr = new XmlNamespaceManager(nav.NameTable); mgr.AddNamespace("g", "http://base.google.com/ns/1.0"); foreach (XPathNavigator item in doc.CreateNavigator().Select("rss/channel/item")) { foreach (XPathNavigator link in item.Select("g:image_link", mgr)) { Console.WriteLine(link.Value); } }