[英]Find first item inside angular brackets after occurrence of other item, using RegEx, in C#
我有一个类似xml的文本,在其中我想找到在某种模式的首次出现时出现的项:通常:
...
<PropertyGroup><name>true</name></PropertyGroup><PropertyGroup>....
....
也可能是
...
<PropertyGroup>
<name>
true</name>
</PropertyGroup>
...
<PropertyGroup>
...
在上面,我需要提取“名称”。
我最初的假设是所有事件都在同一行中,并且我使用字符串属性编写了代码,但是要考虑所有可能性非常困难,只有RegEx可以救我。
我只是不知道怎么写...
我开始是这样的:
Regex regex = new Regex("(?<=<PropertyGroup>#)<+");
Match matches = regex.Matches(Text)[0];
MessageBox.Show(matches.ToString());
我认为这会找到<PropertyGroup>
之后的第一个项目,但是我不知道如何使它得到尖括号内的项目...(可能在一个或多个换行符和/或空格之后)。
我知道有用于解析xml的实用程序,但是我正在寻找可在ac#程序中插入的简单内容
有人可以帮帮我吗 ? 非常感谢你。
编辑:实际文件内容(我正在测试的文件内容,没有奇怪的空格):
<?xml version="1.0" ?><Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets">
<Import xxx/>
</ImportGroup>
<PropertyGroup><myProp>true</myProp></PropertyGroup><PropertyGroup Label="UserMacros"/>
<PropertyGroup/>
<!--maybe other stuff -->
</Project>
使用LINQ to XML实际上非常简单,并且比使用正则表达式更可靠:
using System.Xml.Linq;
...
XElement xmlTree = XElement.Load(fileName);
XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
List<XElement> properties = (
from propertyGroup in xmlTree.Descendants(ns + "PropertyGroup")
from property in propertyGroup.Elements()
select property
).ToList();
现在, properties
应包含所有PropertyGroup
元素的直接子元素的所有XElement
对象。 您可以通过以下方式获取它们的名称和值:
foreach(var property in properties)
{
string name = property.Name.LocalName;
string value = property.Value;
// process both strings
}
这样,您不必担心任何种类的空格,并且它是从XML检索其他信息的非常可维护和可扩展的解决方案。
此外,通常确实值得一读, 这里是开始的地方 。 这将不是您最后一次需要处理XML文件的时间,并且如果您不必总是找出要解析的正则表达式,您会感到很高兴(让我重复一遍,这通常是不可能的)。
尝试这个:
(?s)<PropertyGroup>\s+<([^>]+)
例:
var result =
Regex.Match(input, @"(?s)<PropertyGroup>\s+<([^>]+)")
.Groups[1].Value;
“我知道有解析xml的实用程序”不,与其说是.net框架中内置的类,还不如说是实用程序。
建议您阅读XmlDocument
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.