简体   繁体   中英

Using Replace when string contains quotes

I read other posts and attempted their solutions, but I can't seem to get it to work for me.

I need to update multiple XML files and change a node value from <Option name="fldsep" value="|" /> <Option name="fldsep" value="|" /> to <Option name="fldsep" value="~" /> .

It works when I do { $_.Replace("|", "~") } | Set-Content $_.FullName { $_.Replace("|", "~") } | Set-Content $_.FullName and updates the XML files perfectly, but I don't want it to overwrite other | that are present.

I tried doing:

{ $_.Replace('<Option name="fldsep" value="|" /> ','<Option name="fldsep" value="~" /> ') } | Set-Content $_.FullName

but it won't update the XML file.

Any help would be much appreciated!

Here is the full code for reference:

$pathTest = "C:\Test" Get-ChildItem -path $pathTest -recurse -include "*.tf.*" | % {

    $con = Get-Content $_.FullName
    $con | % { $_.Replace('<Option name="fldsep" value="|" /> ','<Option name="fldsep" value="~" /> ') } | Set-Content $_.FullName

}

The XML section in full looks like this:

<TransformationSourceOptions>
  <Option name="codepage" value="ANSI" /> 
  <Option name="recsep" value="LF" /> 
  <Option name="fieldcount" value="0" /> 
  <Option name="fldsep" value="|" /> 
  <Option name="fldsdelim" value="None" /> 
  <Option name="fldedelim" value="None" /> 
  <Option name="header" value="False" /> 
  <Option name="altfldsep" value="None" /> 
  <Option name="soffset" value="0" /> 
  <Option name="autostyle" value="False" /> 
  <Option name="stylesamplesize" value="5000" /> 
  <Option name="lstrip" value="False" /> 
  <Option name="tstrip" value="False" /> 
  <Option name="field1isrectypeid" value="False" /> 
  <Option name="nullind" value="none" /> 
  <Option name="emptyfieldsnull" value="False" /> 
  <Option name="numericformatnormalization" value="False" /> 
  <Option name="layoutmismatch" value="0" /> 
</TransformationSourceOptions>

If you want to change the value of an attribute in an XML document, utilize the built-in support for XML!

# Load xml doc
$TransformDoc = [xml](Get-Content .\options.xml)

# Find option node and change value of "value" attribute
$TransformDoc.SelectSingleNode('//Option[@name="fldsep"]').value = "~"

# Save your changes to the document
$TransformDoc.Save("options.xml")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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