有什么方法只截取Xml里面的一部分么。

fullisnull 2003-10-25 09:54:36
<data>
<person>1</person>
<person>2</person>
<person>3</person>
<person>4</person>
<person>5</person>
<data>

我想用一个函数GetXml(int star, int end)得到其中<person>元素;
比如GetXml(2, 4)得到的是:
<data>
<person>2</person>
<person>3</person>
<person>4</person>
<data>

诚等兄弟们来帮忙。最好是能够是用类库里面的函数;尽量的简单。
...全文
122 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
readeranddataset 2003-10-25
  • 打赏
  • 举报
回复
谢谢。真是好人。
saucer 2003-10-25
  • 打赏
  • 举报
回复
basically, it uses an XPath to select all nodes whose person's value is < start or > end, then remove those nodes

String.Format("data/person[. < {0} or . > {1}]", 2, 4)
==>
"data/person[. < 2 or . > 4]"

//the following method has a side effect
XmlDocument GetXmlDoc( XmlDocument xmldocAll, int nStart, int nEnd)
{
foreach (XmlNode node in xmldocAll.SelectNodes(String.Format("data/person[. < {0} or . > {1}]", start, end)))
xmldocAll.DocumentElement.RemoveChild(node);

return xmldocAll;

}


if you don't want xmldocAll to be changed, clone one first

XmlDocument GetXmlDoc( XmlDocument xmldocAll, int nStart, int nEnd)
{
XmlDocument doc = (XmlDocument)xmldocAll.CloneNode(true);
foreach (XmlNode node in doc.SelectNodes(String.Format("data/person[. < {0} or . > {1}]", start, end)))
doc.DocumentElement.RemoveChild(node);

return doc;

}


readeranddataset 2003-10-25
  • 打赏
  • 举报
回复
[. < {0} or . > {1}] 呵呵竟让我看糊涂了。我分出来看,哎就清晰了。
谢谢。我看懂了。就揭贴。
fullisnull 2003-10-25
  • 打赏
  • 举报
回复
谢谢两位。
可能我有些菜。
foreach (XmlNode node in doc.SelectNodes(String.Format("data/person[. < {0} or . > {1}]", start, end)))
上面一行我还是有点不明白,我去查查。
我把函数再定义一下。希望大家帮帮忙。

XmlDocument GetXmlDoc( XmlDocument xmldocAll, int nStart, int nEnd);
saucer 2003-10-25
  • 打赏
  • 举报
回复
your xml is invalid, change the last <data> to </data>, try

using System;
using System.Xml;

static void GetXml(XmlDocument doc, int start, int end)
{
foreach (XmlNode node in doc.SelectNodes(String.Format("data/person[. < {0} or . > {1}]", start, end)))
doc.DocumentElement.RemoveChild(node);

}

static void Test5()
{

XmlDocument xmldoc = new XmlDocument();

xmldoc.Load("data.xml");

GetXml(xmldoc, 2,4);

Console.WriteLine(xmldoc.InnerXml);
}
cnhgj 2003-10-25
  • 打赏
  • 举报
回复
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(@"c:\test.xml");
XmlNodeList nodelist = xmldoc.GetElementsByTagName["person"];
for(int i=0;i<nodelist.Length-1;i++)
{
if (Convert.ToInt32(nodelist[i].InnerText) >=2 || Convert.ToInt32(nodelist[i].InnerText) <=4)
........................
}
nonesharp 2003-10-25
  • 打赏
  • 举报
回复
请教wangj2001(乡村酒吧) ,正则表达式如何实现XPATH的功能?
wangj2001 2003-10-25
  • 打赏
  • 举报
回复
最方便的是用正则
fullisnull 2003-10-25
  • 打赏
  • 举报
回复
怎么搞的啊。
我的总打不开管理的网页啊。
打开后就总是来到了这里。

110,567

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧