2014-09-12 87 views
0

我需要在循环中处理此处显示的字符串。该字符串将是任何标准标记。 为如:C#字符串操作来查找在两个指定字符串中出现的所有字符串

<?xml version="1.0" encoding="utf-8"?> 
<article> 
    <blog> 
    <title> this is a title </title> 
    <firstname>Karan</firstname> 
    <lastname>Johar</lastname> 
    </blog> 
    <blog> 
    <title> this is a title </title> 
    <firstname>Karan</firstname> 
    <lastname>Johar</lastname> 
    </blog> 
    <blog> 
    <title> this is a title </title> 
    <firstname>Karan</firstname> 
    <lastname>Johar</lastname> 
    </blog> 
</article> 

我需要做的是让内容的每次出现<title> ...</title> 之间,然后依次将它们传递到另一个函数,当他们来了。

任何人都可以请指导?

+0

你知道的XPath? http://en.wikipedia.org/wiki/XPath – BlackBear 2014-09-12 11:02:20

+0

可能的重复[如何在C#中使用Xpath读取XML](http://stackoverflow.com/questions/9511608/how-to-read-xml-in- c-sharp-using-xpath) – BlackBear 2014-09-12 11:03:28

+0

没有XPath无法使用......因为这不是真的保证是一个有效的XML标记......字符串操作是唯一的途径。 – 2014-09-12 11:04:22

回答

0

选项1:

如果您确定输入的文件将有新的线路,那么你可以尝试逐行读取内容线,并检查是否在该行存在于您的字符串,然后通过该行的

+0

不,那不能保证他们都会换新线 – 2014-09-12 11:05:50

+0

好的,你想要发送给你的另一种方法。 – Prashant19sep 2014-09-12 11:21:54

+0

请参阅上述注释 – 2014-09-12 11:26:30

0

正如你说你有一个字符串,假设你想阅读所有书籍,并将它们传递到另一个函数作为一个列表或串行

List<titles> titlesList=new List<string>(); 
MatchCollection collection = Regex.Matches(XmlDocument, "<title>(?<data>.*?)<.title>"); 
foreach (Match x in collection) 
{ 
    string text=x.Group["data"].Value; 
    Func(text); 
    titlesList.add(text); 
} 

Func(titlesList); 
+0

为什么将Func()调用移入循环?它应该留在循环之后。或者,根本不要使用列表,并为每个单独的匹配调用func。 – 2014-09-12 11:15:38

+0

此外,我会更改正则表达式,如下所示:'(?<data>^<*?)'(未测试)含义:首先停止匹配'<',并要求结束标记中的/ – 2014-09-12 11:17:57

+0

@Kris,我想他是正确的,当他搬进里面...阐述了需求...我需要将输入字符串写入pdf,所以我上面写的函数将用于格式化标题部分,其余部分将是纯文本。所以我之前提到的字符串操作的原因是我需要打印输出,因为标题标签的内容有格式化,其余没有格式化...我的意思是两个写入都必须按顺序完成...我不能拿一个集合,然后做格式化 – 2014-09-12 11:22:33