替换xml文件中的内部文本

时间:2013-12-16 06:12:28

标签: vb.net visual-studio-2010 visual-studio-2008

我找到了这个表达,

^[<conf-start a-z0-9- =""/><month></month>]+

匹配源字符串

<conf-start iso-8601-date="2011-03-04"><day>04</day><month>March</month><year>2011</year></conf-start>

但我无法取代3月到03年的月份,例如3月应该替换为03

我尝试了以下代码,

    Dim mydir As String = TextBox1.Text
    Dim filePath As String = TextBox1.Text
    Dim directory1 As String = Path.GetDirectoryName(filePath)
    Dim split As String() = filePath.Split("\")
    Dim parentFolder As String = split(split.Length - 2)

    Dim outputLines As New List(Of String)()
    Dim stringToMatch As String = "^[<conf-start a-z0-9- =""/><month>March</month>]+"
    Dim replacementString As String = "^[<conf-start a-z0-9- =""/><month>03</month>]+"

    For Each line As String In System.IO.File.ReadAllLines(TextBox1.Text & "\" & parentFolder & ".xml")
        Dim matchFound As Boolean
        matchFound = line.Contains(stringToMatch)

        If matchFound Then
            ' Replace line with string
            outputLines.Add(replacementString)
        Else
            outputLines.Add(line)
        End If
    Next
    System.IO.File.WriteAllLines(TextBox1.Text & "\" & parentFolder & ".xml", outputLines.ToArray(), Encoding.UTF8)

但我无法在我的xml文件中找到更改。 所以任何人请帮助我。 仍然坚持这个问题。

1 个答案:

答案 0 :(得分:0)

您可以改为使用LINQ to XMLXML literals

示例:

' Load the file '
Dim yourXml = XDocument.Load("your_path_to_the_file.xml").Root

' Change each monthname to the number of the month
For Each elem in yourXml ...<conf-start>.<month>
    elem.value = DateTime.ParseExact(elem.value, "MMMM", System.Globalization.CultureInfo.InvariantCulture).Month
Next

' save file
yourXml.Save("your_path_to_the_file.xml")