通过使用LINQ 2 XML计算某个字符串来生成文件的xml属性值?

时间:2017-12-24 13:01:09

标签: c# xml

我有一些XML文件,其中可能包含节点<disp-formula id="deqn*">,并且每个节点都有一个名为\tag的字符串。现在,关键字\tag的数量可以是每个节点<disp-formula id="deqn*">中的一个或多个。

我想从1开始生成属性值id,然后使用<disp-formula id="deqn*">计数找到的每个\tag增加到+1。

示例数据:

<disp-formula id="deqn*">...\tag...</disp-formula>
<disp-formula id="deqn*">...\tag...\tag...\tag ...</disp-formula>
<disp-formula id="deqn*">...\tag ...</disp-formula>
<disp-formula id="deqn*">...\tag...\tag ...</disp-formula>

预期修改:

<disp-formula id="deqn1">...\tag...</disp-formula>
<disp-formula id="deqn2-4">...\tag...\tag...\tag ...</disp-formula>
<disp-formula id="deqn5">...\tag ...</disp-formula>
<disp-formula id="deqn6-7">...\tag...\tag ...</disp-formula>

为了生成某个字符串的数字,我基本上使用以下过程:

string inputText = File.ReadAllText(@"C:\temp\sample.xml");
string findText = @"*";  

int matchCount = inputText.Split(findText.ToCharArray()).Length - 1;  

if (matchCount > 0)  
{  
    for (int counter = 1; counter <= matchCount; counter++)  
    {  
        var regex = new Regex(Regex.Escape(findText));  
        inputText = regex.Replace(inputText, counter.ToString(), 1);  
    }  
}

但我无法弄清楚如何在此方法中添加\tag计数器,或者如何使用LINQ2XML完成此工作? 有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

试试这个;

XDocument doc = XDocument.Load("disp.xml");
var deqns = doc.Descendants("disp-formula");
int countIndex = 1;
foreach (var deqn in deqns)
{
    var matchCount = deqn.Value.Select((c, i) => deqn.Value.Substring(i)).Count(sub => sub.StartsWith("\\tag"));
    if (matchCount > 0)
    {
        int lastMatchCount = countIndex + matchCount - 1;
        var attribute = string.Format("deqn-{0}", countIndex);
        if (lastMatchCount > countIndex)
        {
            attribute = attribute + "-" + lastMatchCount;
        }
        deqn.Attribute("id").Value = attribute;
        countIndex = lastMatchCount + 1;
    }
}
doc.Save("disptarget.xml");

答案 1 :(得分:0)

static void Main(string[] args)
{
    var xmlStr =
        @"<root>
            <disp-formula id='deqn*'>...\tag...</disp-formula>
            <disp-formula id='deqn*'>...\tag...\tag...\tag ...</disp-formula>
            <disp-formula id='deqn*'>...\tag ...</disp-formula>
            <disp-formula id='deqn*'>...\tag...\tag ...</disp-formula>
        </root>";

    var xml = XElement.Parse(xmlStr);

    int x = 0;
    xml.Elements().ToList().ForEach(node =>
    {
        var count = Regex.Matches(node.Value, @"\\tag").Count;
        if (count > 0)
        {
            string start = (x + 1).ToString();
            string end = (x += count).ToString();
            string period = end == start ? start : $"{start}-{end}";
            node.Attribute("id").Value = "deqn" + period;
        }
    });

    Console.WriteLine(xml);
}