我有一个xml如下所示:
<?xml version="1.0" encoding="utf-8"?>
<Query_advanced>
<Query>hy</Query>
<Attribute Name1="Patient's Age" Value1="23" xmlns="xyz"/>
<Attribute Name1="Patient's Birth Date" Value1="24/12/1988" xmlns="xyz"/>
<Attribute Name1="Patient's Name" Value1="xyz" xmlns="xyz" />
</Query_advanced>
我需要通读xml来获取Name1和Value1的值,但我无法使用xmlns。有什么办法可以吗?我尝试过使用:
XmlNamespaceManager xnm = new XmlNamespaceManager(xdoc.NameTable);
xnm.RemoveNamespace("Attribute", "xyz");
答案 0 :(得分:1)
我认为您不必删除命名空间,但是您必须将其添加到XmlNameSpaceManager,以便使用前缀(如@John Saunders注释),例如,在XPath表达式中。
试试这个:
XmlNamespaceManager xnm = new XmlNamespaceManager(xdoc.NameTable);
xnm.AddNamespace("a", "xyz");
// Cycle through the Attribute nodes
foreach (XmlNode node in xdoc.SelectNodes("//Query_advanced/a:Attribute", xnm))
{
// And read the attributes of the node
string NameAttribute = node.Attributes["Name1"].Value;
string ValueAttribute = node.Attributes["Value1"].Value;
}
答案 1 :(得分:0)
如果您有文件,请使用XmlReader
或XmlTextReader
。
这是一个例子: http://msdn.microsoft.com/en-us/library/cc189056(v=vs.95).aspx
在您的示例中,Attribute
是一个xml标记,而不是命名空间。 Name1
和Value1
是标记Attribute
的xml属性。
因此,您需要阅读标记Attribute
的属性。
让xmlString
是您要解析的xml:
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
while(reader.ReadToFollowing("Attribute")){ //loop read Attribute tag
reader.MoveToFirstAttribute();
string Name1 = reader.Value; //do something with Name1
reader.MoveToNextAttribute();
string Value1 = reader.Value; //do something with Value1
}
}
答案 2 :(得分:0)
谢谢所有建议!我设法这样做了:
private void QueryXML() {
XmlDocument query_xml = new XmlDocument();
query_xml.Load("Query_1.xml");
XmlNodeList elements = query_xml.GetElementsByTagName("Attribute");
string[] s = new string[elements.Count];
for (int i = 0; i < elements.Count; i++)
{
string attrVal = elements[i].Attributes["Value1"].Value;
Console.Writeline(attrval)
}
非常感谢! :)