从XML中提取带有空格的文件路径和参数作为不同的字符串

时间:2018-12-12 10:38:45

标签: c# xml split filepath

我有一个XML文件,其中包含一些有关从exe启动应用程序的信息。喜欢:

<details>
    C:\Program Files\...\abc.exe -env env -direnv direnv
</details>

我需要拆分为exe路径的第一部分,其余部分作为参数。但是当我按空格分开时,我只会得到C:\Program。是否有另一种解决方案来实现输出为:

  

string [0] = C:\ Program Files ... \ abc.exe
  字符串[1] = -env env -direnv
  direnv

编辑用于从XML提取的代码:

XMLNodeLst = GetNodeFromXML().SelectNodes("Path");

if (XMLNodeLst != null)
{
    foreach (XmlNode xmlNode in XMLNodeLst)
    {
        foreach (XmlNode pathNode in xmlNode.ChildNodes)
        {
            Match m = Regex.Match(source, pathNode.Name, RegexOptions.IgnoreCase);
            if (m.Success)
            {
                installPath = pathNode.InnerText.Trim();
                break;
            }
            else
            {
                logs.Error("No corresponding value in settings for the provided source name. Please check again!");
                MessageBox.Show("No corresponding value in settings for the provided source name. Please check again!");
                Environment.Exit(-1);
            }
        }
    }
}

XML:

<?xml version="1.0" encoding="utf-8" ?>
<Path>
  <details>
    C:\Program Files\...\abc.exe -env env -direnv direnv
  </details>
</Path>

要拆分:

string[] configs = installPath.Trim().Split(' ');
exePath = configs[0];
exeArgs = installPath.Remove(0, installPath.IndexOf(' ') + 1);

3 个答案:

答案 0 :(得分:0)

可用于解析字符串的类的示例:

public class ArgumentPathResult {
    public string Path;
    public List<string> Arguments = new List<string>();
}
// Define other methods and classes here
public static class ArgumentPathParser {
    public static ArgumentPathResult ParsePath(string path) {
        ArgumentPathResult result = new ArgumentPathResult();
        string resultString = "";
        foreach(char c in path){
            resultString += c;
            if(resultString.Contains(".exe")){
                break;
            }
        }
        result.Path = resultString;
        result.Arguments = path.Replace(resultString, "")
            .Split('-')
            .Skip(1)
            .ToList();
        return result;
    }
}

用法示例:

string path = @"C:\Program Files\...\abc.exe -env env -direnv direnv";
ArgumentPathResult result = ArgumentPathParser.ParsePath(path);

结果对象将包含您的Path作为一个变量,以及参数和值对"env env""direnv direnv"的列表

答案 1 :(得分:0)

您可能会在正向查找和正向查找之间进行拆分,以断言左侧是.exe,后跟一个空格,右边是一个破折号,后跟1+个非空白字符:

(?<=\.exe) (?=-\S+)

Regex demo

var installPath = @"C:\Program Files\...\abc.exe -env env -direnv direnv";
string[] configs = Regex.Split(installPath, @"(?<=\.exe) (?=-\S+)");
var exePath = configs[0];
Console.WriteLine(exePath); // C:\Program Files\...\abc.exe

请参见C# demo

答案 2 :(得分:0)

var splitted = pathNode.InnerText.Trim()
    .Split(new string[] { ".exe " }, StringSplitOptions.None);

var path = splitted[0] + ".exe";
var args = splitted[1];