2017-03-24 146 views
1

我在PowerShell中首次使用XML文件。我有一个简单的脚本失败。我需要使用web请求来获取XML内容,然后将其保存到文件夹中供以后处理。Powershell:将XML写入文件

下面是代码:

$IP = 8.8.8.8 
$ipgeo = new-object System.Xml.XmlDocument 
$ipgeo = ([xml](Invoke-WebRequest "http://freegeoip.net/xml/$IP").Content).Response 
$ipgeo.save("c:\ipgeo\IPXML\$IP.xml") 

当我运行它,我得到以下错误:

Method invocation failed because [System.Xml.XmlElement] does not contain a method named 'save'. At line:3 char:1 
+ $ipgeo.save("c:\ipgeo\IPXML\$IP.xml") 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
+ CategoryInfo: InvalidOperation: (save:String) [], RuntimeException 
+ FullyQualifiedErrorId : MethodNotFound 

我在做什么错?

+0

@CodeCaster'System.Xml.XmlElement'不包含命名方法“保存”或'保存' - 投射是问题,所以改变大小写不会有帮助 – arco444

+0

@arco你是对的。 'System.Xml.XmlDocument' [_does_有一个Save()方法](https://msdn.microsoft.com/en-us/library/dw229a22(v = vs.110).aspx),但它们覆盖'$ ipgeo'。 – CodeCaster

+0

@CodeCaster它*是*给出这个错误。这是因为'.Response'被选中,它是一个'XmlElement',所以如果你用下面的代码行中的其他东西覆盖它,那么你实例化的内容就不重要了。 – arco444

回答

2

可以通过引用根节点的OuterXml财产保存XML文档的一个子集,你想:

# instead of $ipgeo.Save("c:\ipgeo\IPXML\$IP.xml") 
$ipgeo.OuterXml |Out-File "c:\ipgeo\IPXML\$IP.xml" 
+0

工作正常!非常感谢你的快速反应! – Doug

+0

还有一个问题,我如何才能读取我刚刚写的XML文件?我试过:$ ipgeo = [System.Xml.XmlDocument](Get-Content c:\ ipgeo \ IPXML \ $ IP.xml),但没有返回任何内容。 – Doug

+0

我想通了。我需要使用:$ ipgeo =([System.Xml.XmlDocument](Get-Content c:\ ipgeo \ IPXML \ $ IP.xml))。 – Doug