簡體   English   中英

在 vb.net 中並使用 XML 文檔,如何用值替換某些字符串,而不管它在哪個節點?

[英]In vb.net and using the XML document, How can I replace certain strings with values regardless of what node it is in?

在 vb.net 中並使用 XML 文檔,我如何用值替換某些字符串 - 無論它位於哪個節點 - 然后將 xml 文件寫回? 我不想硬編碼節點名稱,因為我不知道節點名稱將來是否會更改。

我有一個 xml 文件,其中包含由 %% 包圍的不同變量。 我需要找到它們並根據需要更改它們的值。

變量是:%ip% %netmask-bits% %gateway% %ns% %hostname% %password% %tz% %key% %server% %mac-windows%

我開始的VB代碼是:

    Imports System.Xml

    Dim xmlNode1 As XmlNode
    Dim strIp As String
    Dim strIPNewValue As String = "1.1.1.1"
    Dim bSuccess As Boolean = False

    Dim myXmlDocument As XmlDocument = New XmlDocument()

    myXmlDocument.Load("unattend.xml")

    xmlNode1 = myXmlDocument.DocumentElement

    ' Fields to match.
    strIp = "%ip%"

    ' Just do one pass threw and change the variables. 
    ' I don't want to hard code node names as I don't know if the node names
    ' will change in the future.

    ' Not sure how to proceed...


    If bSuccess = True Then
        myXmlDocument.Save("unattend.xml")
        Console.WriteLine("The XML file was saved successfully.")
    Else
        Console.WriteLine("The entry was not found.")
    End If

unattend.xml XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
<settings pass="windowsPE">
    <component xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="Microsoft-Windows-International-Core-WinPE" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
        <SetupUILanguage>
            <UILanguage>en-US</UILanguage>
        </SetupUILanguage>
        <InputLocale>en-US</InputLocale>
        <SystemLocale>en-US</SystemLocale>
        <UILanguage>en-US</UILanguage>
        <UILanguageFallback>en-US</UILanguageFallback>
        <UserLocale>en-US</UserLocale>
    </component>
    <component xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="Microsoft-Windows-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
        <DiskConfiguration>
            <Disk wcm:action="add">
                <CreatePartitions>
                    <CreatePartition wcm:action="add">
                        <Order>1</Order>
                        <Size>350</Size>
                        <Type>Primary</Type>
                    </CreatePartition>
                    <CreatePartition wcm:action="add">
                        <Extend>true</Extend>
                        <Order>2</Order>
                        <Type>Primary</Type>
                    </CreatePartition>
                </CreatePartitions>
                <ModifyPartitions>
                    <ModifyPartition wcm:action="add">
                        <Active>true</Active>
                        <Format>NTFS</Format>
                        <Label>Boot</Label>
                        <Order>1</Order>
                        <PartitionID>1</PartitionID>
                    </ModifyPartition>
                    <ModifyPartition wcm:action="add">
                        <Format>NTFS</Format>
                        <Label>System</Label>
                        <Order>2</Order>
                        <PartitionID>2</PartitionID>
                    </ModifyPartition>
                </ModifyPartitions>
                <DiskID>0</DiskID>
                <WillWipeDisk>true</WillWipeDisk>
            </Disk>
        </DiskConfiguration>
        <ImageInstall>
            <OSImage>
                <InstallFrom>
                    <MetaData wcm:action="add">
                        <Key>/IMAGE/NAME</Key>
                        <Value>Windows Server 2012 R2 SERVERSTANDARD</Value>
                    </MetaData>
                </InstallFrom>
                <InstallTo>
                    <DiskID>0</DiskID>
                    <PartitionID>2</PartitionID>
                </InstallTo>
            </OSImage>
        </ImageInstall>
        <UserData>
            <ProductKey>
                <Key>%key%</Key>
                <WillShowUI>Never</WillShowUI>
            </ProductKey>
            <AcceptEula>true</AcceptEula>
            <FullName>Administrator</FullName>
            <Organization> </Organization>
        </UserData>
    </component>
</settings>
<settings pass="specialize">
    <component xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
        <OEMInformation>
            <HelpCustomized>false</HelpCustomized>
        </OEMInformation>
        <ComputerName>%hostname%</ComputerName>
        <TimeZone>%tz%</TimeZone>
        <RegisteredOwner/>
    </component>
    <component xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="Microsoft-Windows-Security-SPP-UX" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
        <SkipAutoActivation>true</SkipAutoActivation>
    </component>
    <component name="Microsoft-Windows-TCPIP" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <Interfaces>
            <Interface wcm:action="add">
                <Identifier>%mac-windows%</Identifier> 
                <Ipv4Settings>
                    <DhcpEnabled>false</DhcpEnabled> 
                    <Metric>20</Metric> 
                    <RouterDiscoveryEnabled>false</RouterDiscoveryEnabled> 
                </Ipv4Settings>
                <UnicastIpAddresses>
                    <IpAddress wcm:action="add" wcm:keyValue="1">%ip%/%netmask-bits%</IpAddress> 
                </UnicastIpAddresses>
                <Routes>
                    <Route wcm:action="add">
                        <Identifier>0</Identifier> 
                        <Prefix>0.0.0.0/0</Prefix> 
                        <Metric>20</Metric> 
                        <NextHopAddress>%gateway%</NextHopAddress> 
                    </Route>
                </Routes>
                <DNSServerSearchOrder>
                </DNSServerSearchOrder>
            </Interface>
        </Interfaces>
    </component>
    <component name="Microsoft-Windows-DNS-Client" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <Interfaces>
            <Interface wcm:action="add">
                <Identifier>%mac-windows%</Identifier>
                <DNSServerSearchOrder>
                    <IpAddress wcm:action="add" wcm:keyValue="1">%ns%</IpAddress>
                </DNSServerSearchOrder>
            </Interface>
        </Interfaces>
    </component>
    <component name="Microsoft-Windows-Deployment" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <RunSynchronous>
            <RunSynchronousCommand wcm:action="add">
                <Order>1</Order>
                <Path>cmd.exe /c powershell Invoke-WebRequest "http://%server%/installation-finished"</Path>
                <Description>Post-installation notification</Description>
            </RunSynchronousCommand>
        </RunSynchronous>
    </component>
</settings>
<settings pass="oobeSystem">
    <component xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
        <OOBE>
            <HideEULAPage>true</HideEULAPage>
            <HideLocalAccountScreen>true</HideLocalAccountScreen>
            <HideOEMRegistrationScreen>true</HideOEMRegistrationScreen>
            <HideOnlineAccountScreens>true</HideOnlineAccountScreens>
            <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE>
            <NetworkLocation>Home</NetworkLocation>
            <ProtectYourPC>1</ProtectYourPC>
        </OOBE>
        <UserAccounts>
            <AdministratorPassword>
                <Value>%password%</Value>
                <PlainText>true</PlainText>
            </AdministratorPassword>
        </UserAccounts>
        <RegisteredOwner/>
    </component>
</settings>
<settings pass="offlineServicing">
     <component     xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="Microsoft-Windows-   LUA-Settings" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35"    language="neutral" versionScope="nonSxS">
        <EnableLUA>false</EnableLUA>
       </component>
   </settings>
  </unattend>

由於文件不是很大,我可能只是將它讀入一個字符串變量(使用 System.IO.File.ReadAllText),然后為每個關鍵字運行 String.Replace 方法。

    Imports System.Xml
    Module Module1
    Sub Main()
    Dim DocumentFileLocation As String = "your xml document location"
    Dim DocumentString As String = IO.File.ReadAllText(DocumentFileLocation)
    Dim Document = XmlReader.Create(DocumentString) 'do whatever you want in the xml
    ReplaceContentAndSave(DocumentString.Replace(char1, char2), DocumentFileLocation)
    'Your Document Reading Loop
    Do While Document.Read
    'do something
    Loop
    End Sub
    
    Sub ReplaceContentAndSave(newContent As String, path As String)
    My.Computer.FileSystem.WriteAllText(path, newContent, False)
    End Sub
    
    End Module

如果它不起作用,那是因為我沒有測試過

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM