removing namespace from xml
I have an xml as shown:
<?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>
I need to read through the xml to get the values of Name1 and of Value1, but im unable to do so with the xmlns there. Is there any way i co开发者_开发问答uld do so? Ive tried using:
XmlNamespaceManager xnm = new XmlNamespaceManager(xdoc.NameTable);
xnm.RemoveNamespace("Attribute", "xyz");
I think you've not to remove the namespace, but you've to add it to the XmlNameSpaceManager, in order to use a prefix (as @John Saunders comments), for example, in a XPath expression.
Try this:
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;
}
Use XmlReader
or XmlTextReader
if you have a file.
Here an example: http://msdn.microsoft.com/en-us/library/cc189056(v=vs.95).aspx
In your example Attribute
is a xml tag, not a namespace. Name1
and Value1
are xml attributes of the tag Attribute
.
So you need to read the attributes of the tag Attribute
.
Let xmlString
is the xml you want to parse:
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
}
}
THanks for all your suggestions! I managed to do it this way:
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)
}
Thanks a bunch! :)
精彩评论