从字符串中拆分值

时间:2016-12-07 09:40:45

标签: c#

我在字符串中有xml数据,我希望它能分割,我想在Lable中显示结果。

这是我的代码:

string param = <HCToolParameters><BatchId>12</BatchId><HCUser>Admin</HCUser</HCToolParameters>;
var a = param.Split(new string[] { "<HCToolParameters>" }, StringSplitOptions.RemoveEmptyEntries);
var b = param.Split(new string[] { "<BatchId>12</BatchId>" }, StringSplitOptions.RemoveEmptyEntries);
var c = param.Split(new string[] { "<HCUser>Admin</HCUser>" }, StringSplitOptions.RemoveEmptyEntries);
var d = param.Split(new string[] { "</HCToolParameters>" }, StringSplitOptions.RemoveEmptyEntries);

示例:

String value = 
<HCToolParameters><BatchId>12</BatchId><HCUser>Admin</HCUser></HCToolParameters>

预期结果:

<HCToolParameters>
 <BatchId>12</BatchId>
 <HCUser>Admin</HCUser>
</HCToolParameters>

3 个答案:

答案 0 :(得分:1)

从我在乞讨中看到你有效的xml所以,停止拆分并使用Xml Parser!

string param =@"<HCToolParameters><BatchId>12</BatchId><HCUser>Admin</HCUser></HCToolParameters>";

XDocument doc = XDocument.Parse(param);

Console.WriteLine(doc.ToString());

答案 1 :(得分:0)

嗯,你可以轻松做到这一点:

value = value.Replace("><", ">" + Environment.NewLine + "<");

这可以在你的例子中解决并且很容易,...如果你需要它作为数组(我不知道为什么你会这样尝试:

var array = value.Replace("><", ">#<").Split('#');

答案 2 :(得分:0)

您可以使用XmlTextWriter.Formatting = Formatting.Indented;因为看到的是,您希望格式化XML字符串。这个功能可能适合你

public static String FormatMyXML(String SomeXML)
{
    String Result = "";
    MemoryStream mStream = new MemoryStream();
    XmlTextWriter wrtr = new XmlTextWriter(mStream, Encoding.Unicode);
    XmlDocument document   = new XmlDocument();
    try
    {
        document.LoadXml(SomeXML);
        wrtr.Formatting = Formatting.Indented;
        document.WriteContentTo(wrtr);
        wrtr.Flush();
        mStream.Flush();
        mStream.Position = 0;
        StreamReader sReader = new StreamReader(mStream);
        String FormattedXML = sReader.ReadToEnd();
        Result = FormattedXML;
    }
    catch (XmlException)
    {
    }
    mStream.Close();
    wrtr.Close();
    return Result;
}