PowerShell:将XML写入文件

4

我第一次在PowerShell中使用XML文件。我有一个简单的脚本失败了。我需要使用web-request获取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

我做错了什么?

@CodeCaster System.Xml.XmlElement 没有名为 'save' 或 'Save' 的方法 - 问题在于强制转换,因此更改大小写不会有所帮助。 - arco444
@arco 你说得对。System.Xml.XmlDocument确实有一个Save()方法,但他们正在覆盖$ipgeo - CodeCaster
@CodeCaster 嗯,它确实会出现那个错误。这是因为选择了.Response,它一个XmlElement,所以如果在下一行代码中用其他东西覆盖它,实例化什么并不重要。 - arco444
@CodeCaster 对不起,我以为我格式化得不正确。 - Doug
1
@CodeCaster 不,你不需要。 - Mathias R. Jessen
@Mathias 谢谢。我不知道自己当时是怎么搞错了,但那对于PowerShell来说肯定不对。评论已删除。 - CodeCaster
1个回答

6

您可以通过引用您想要的根节点的OuterXml属性,保存Xml文档的子集:

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

1
成功了!非常感谢您的超快速回复! - Doug
还有一个问题,我该如何读取刚刚写入的XML文件?我尝试了:$ipgeo = [System.Xml.XmlDocument](Get-Content c:\ipgeo\IPXML$IP.xml),但是没有返回任何内容。 - Doug
我解决了。我需要使用:$ipgeo = ([System.Xml.XmlDocument](Get-Content c:\ipgeo\IPXML$IP.xml)).Response - Doug

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接