이 XML 마크 업에서 선택된 노드 값을 추출하는 방법
문제
아래에 나열된 (표본 - 실제 마크 업이 상당히 더 복잡 할 수 있음) 마크 업 및 제약 조건을 감안할 때, 누구나 { "@@ value1 @@", "@@를 검색하기 위해 전체 나무를 걷는 것보다 솔루션 (C#)을 더 효과적/효율적으로 제안 할 수 있습니다. value2 @@ ","@@ value3 @@ "}, 즉 마크 업이 실제로 사용될 때 교체 될 토큰 목록입니다.
참고 : 마크 업, 마크 업 구조 또는 교체중인 토큰의 형식/이름을 제어 할 수 없습니다.
<markup>
<element1 attributea="blah">@@value1@@</element1>
<element2>@@value2@@</element2>
<element3>
<element3point1>@@value1@@</element3point1>
<element3point2>@@value3@@</element3point2>
<element3point3>apple</element3point3>
<element3>
<element4>pear</element4>
</markup>
해결책
어때요 :
var keys = new HashSet<string>();
Regex.Replace(input, "@@[^@]+@@", match => {
keys.Add(match.Value);
return ""; // doesn't matter
});
foreach (string key in keys) {
Console.WriteLine(key);
}
이것:
- XML을 구문 분석하지 않습니다 (단지 문자열 조작)
- 만 포함합니다 독특한 값 (반환 필요 없음 a
MatchCollection
우리가 원하지 않는 복제물로)
그러나 더 큰 문자열을 만들 수 있으므로 Matches
:
var matches = Regex.Matches(input, "@@[^@]+@@");
var result = matches.Cast<Match>().Select(m => m.Value).Distinct();
foreach (string s in result) {
Console.WriteLine(s);
}
다른 팁
나는 당신의 샘플로 빠른 프로그램을 썼습니다. 이것은 트릭을 수행해야합니다.
class Program
{
//I just copied your stuff to Test.xml
static void Main(string[] args)
{
XDocument doc = XDocument.Load("Test.xml");
var verbs=new Dictionary<string,string>();
//Add the values to replace ehre
verbs.Add("@@value3@@", "mango");
verbs.Add("@@value1@@", "potato");
ReplaceStuff(verbs, doc.Root.Elements());
doc.Save("Test2.xml");
}
//A simple replace class
static void ReplaceStuff(Dictionary<string,string> verbs,IEnumerable<XElement> elements)
{
foreach (var e in elements)
{
if (e.Elements().Count() > 0)
ReplaceStuff(verbs, e.Elements() );
else
{
if (verbs.ContainsKey(e.Value.Trim()))
e.Value = verbs[e.Value];
}
}
}
}
제휴하지 않습니다 StackOverflow