简体   繁体   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?

In vb.net and using the XML document, how do I replace certain strings with values - regardless of what node it is in - and then write the xml file back?在 vb.net 中并使用 XML 文档,我如何用值替换某些字符串 - 无论它位于哪个节点 - 然后将 xml 文件写回? I don't want to hard code node names as I don't know if the node name will change in the future.我不想硬编码节点名称,因为我不知道节点名称将来是否会更改。

I have an xml file with different variables surrounded by %%.我有一个 xml 文件,其中包含由 %% 包围的不同变量。 I need to find them and change their values depending.我需要找到它们并根据需要更改它们的值。

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

VB code that I started is:我开始的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

The unattend.xml XML file: 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

if it doen't work it's becuase I didn't test it out如果它不起作用,那是因为我没有测试过

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM