我想使用c#讀取以下xml。使用C#讀取包含xmlns屬性的xml節點
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core" />
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>
<spring>
<context>
<resource uri="config://spring/objects" />
</context>
<objects xmlns="http://www.springframework.net">
<object></object>
</objects>
</spring>
</configuration>
它不會識別對象節點的xmlns。
string xmlFile = @"App1.config";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFile);
XmlNodeList nodeList = xmlDoc.SelectNodes("configuration/spring/objects/object");
foreach (XmlElement xmlElement in nodeList)
{
string id = xmlElement.GetAttribute("id"); //Output - SimulatorControlTCP
XmlNodeList xmlPropertyNodeList = xmlElement.SelectNodes("property");
foreach (XmlElement xmlPropertyElement in xmlPropertyNodeList)
{
id = xmlPropertyElement.GetAttribute("value");
if ((id.Contains("tcp") || id.Contains("http")) && id.Contains("localhost"))
{
id = id.Replace("localhost","1.1.1.1");
xmlPropertyElement.Attributes[1].Value = id;
xmlDoc.Save(xmlFile);
}
}
}
它不會進入foreach循環。如果我刪除xmlns,那麼上面的代碼工作正常。
只需清楚:在調用XmlDocument.Read之後,您確實會得到一個名爲「objects」的XmlNode,但具有空的XmlAttributeCollection? – 2011-12-28 11:18:52
我已添加代碼。代碼在刪除xmlns屬性後起作用 – user660232 2011-12-28 11:29:53
我在調用XmlDocument.Read之後不會獲取對象節點,因爲它包含xmlns屬性 – user660232 2011-12-28 11:40:36