1

我在阅读 XML 时遇到问题,如下所示:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<connections xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<connection id="1" odcFile="C:\Users\andr\Documents\My Data Sources\ELITE_MSSQLSERVER2012 PSO Reports.odc" keepAlive="1" name="ELITE_MSSQLSERVER2012 PSO Reports" type="5" refreshedVersion="5" background="1">
<dbPr connection="Provider=MSOLAP.5;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=PSO;Data Source=ELITE\MSSQLSERVER2012;MDX Compatibility=1;Safety Options=2;MDX Missing Member Mode=Error" command="Reports" commandType="1"/>
<olapPr sendLocale="1" rowDrillCount="1000"/>
</connection>
</connections>

(它实际上是 *.xlsx 包中的 connection.xml 文件)。我试图在 XDocument 的帮助下阅读它。我需要更改“odcFile”属性。问题在于它将整个事物作为没有子元素的单个元素读取。为什么这样?XML 看起来很正常。或者也许有另一种解决方法可以做到这一点?

4

2 回答 2

1

Try using System.Xml.Document instead, if you can access an actual xml file. Not sure what you mean by "it's actually a connection.xml file in *.xlsx package":

using System.Xml

XmlDocument dom = new XmlDocument();
XmlNone root;

dom.Load(fullpath);

root = dom.DocumentElement;
于 2013-09-09T23:15:29.030 回答
1

查询此文档时必须使用适当的XNamespace实例。那是因为您的<connections>标签将默认命名空间设置为"http://schemas.openxmlformats.org/spreadsheetml/2006/main".

var xDoc = XDocument.Load("Input.txt");
var ns = XNamespace.Get("http://schemas.openxmlformats.org/spreadsheetml/2006/main");

var odcFile = xDoc.Root.Elements(ns + "connection")
                       .FirstOrDefault(x => (int)x.Attribute("id") == 1)
                       .Attribute("odcFile");

odcFile.Value = "newOdcValue";

xDoc.Save("Input.txt");
于 2013-09-10T18:13:59.153 回答