xmlns attribute won't let me parse [duplicate]

2019-03-06 17:14发布

问题:

This question already has an answer here:

  • XPath select node with namespace 6 answers

I've been trying to parse this XML file for the last hour

<?xml version="1.0"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
    <name>MEDO PUB</name>
    <SSIDConfig>
        <SSID>
            <hex>4D45444F20505542</hex>
            <name>MEDO PUB</name>
        </SSID>
    </SSIDConfig>
    <connectionType>ESS</connectionType>
    <connectionMode>manual</connectionMode>
    <MSM>
        <security>
            <authEncryption>
                <authentication>WPA2PSK</authentication>
                <encryption>AES</encryption>
                <useOneX>false</useOneX>
            </authEncryption>
            <sharedKey>
                <keyType>passPhrase</keyType>
                <protected>true</protected>
                <keyMaterial>someReallyLongString</keyMaterial>
            </sharedKey>
        </security>
    </MSM>
</WLANProfile>

but I kept getting errors. This is a saved Wi-Fi profile and I used Managed Wifi API to export the XML file. Later, I wanted to parse and read some data from the XML file. I couldn't. After admitting the defeat, I had nothing else to try but modify the XML file. So I tried parsing

<?xml version="1.0"?>
<WLANProfile>
    <name>MEDO PUB</name>
</WLANProfile>

and it worked. xmlns="http://www.microsoft.com/networking/WLAN/profile/v1" was causing the trouble. Why is that?

I'll be generating the XML and reading from it on the fly, so I can't manually open and delete that part from the XML file. How can I fix this?


Using:

Visual C# 2010 Express (Not All-In-One, separate installation)

Windows 8.1 Pro x64

XmlDocument doc = new XmlDocument();
doc.Load("c:/key.xml");
XmlNode node = doc.DocumentElement.SelectSingleNode("//WLANProfile/name");
XMLOutput.Text = node.InnerText;

回答1:

xmlns="...." is default namespace (unprefixed namespace declaration). Note that descendant elements inherit ancestor default namespace implicitly, unless otherwise specified. That means, in this particular XML, all elements are in the default namespace.

To select element in namespace using XPath, you need to register prefix that point to the corresponding namespace first, then use the registered prefix properly in your XPath :

XmlDocument doc = new XmlDocument();
doc.Load("c:/key.xml");
var nsManager = new XmlNamespaceManager(doc.NameTable);
nsManager.Add("d", "http://www.microsoft.com/networking/WLAN/profile/v1");
XmlNode node = doc.DocumentElement.SelectSingleNode("//d:WLANProfile/d:name", nsManager);
XMLOutput.Text = node.InnerText;