You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Hardware表的Settings列XML中提取MacAddress值?

Fixing XML MacAddress Extraction in SQL Server

Hey there! It looks like your current query is pulling the entire <properties> node content instead of targeting the specific MacAddress value—let's get that sorted out.

The Problem with Your Original Query

Your existing statement uses (/properties)[1] in the value() method, which tells SQL Server to return the full contents of the first <properties> node. To grab just the MacAddress, you need to drill down to that specific child node in your XPath expression.

Solution 1: Basic XPath for Directly Nested MacAddress

Assuming your XML structure looks something like this (with MacAddress as a direct child of <properties>):

<properties><MacAddress>AA:BB:CC:DD:EE:FF</MacAddress><otherSetting>sampleValue</otherSetting></properties>

Use this adjusted query to target the MacAddress node directly:

SELECT 
    uri,
    settings.value('(/properties/MacAddress)[1]', 'varchar(50)') AS MacAddress
FROM Hardware
GO
  • The (/properties/MacAddress)[1] XPath locates the first MacAddress child under the root <properties> node.
  • We use varchar(50) as the data type since MAC addresses are typically 17 characters long, giving extra room for any formatting variations.

Solution 2: Handling XML Namespaces

If your XML includes a namespace (like xmlns="http://your-custom-namespace.com"), you'll need to declare it first with WITH XMLNAMESPACES to avoid null results:

WITH XMLNAMESPACES (DEFAULT 'http://your-custom-namespace.com')
SELECT 
    uri,
    settings.value('(/properties/MacAddress)[1]', 'varchar(50)') AS MacAddress
FROM Hardware
GO

Adjust for Deeper Nested Nodes

If MacAddress is nested deeper (e.g., <properties><networkSettings><MacAddress>...</MacAddress></networkSettings></properties>), update the XPath to match the full path:

settings.value('(/properties/networkSettings/MacAddress)[1]', 'varchar(50)') AS MacAddress

Test First with query()

If you're unsure about the exact XPath, use the query() method to preview the node content first:

SELECT 
    uri,
    settings.query('/properties/MacAddress') AS MacAddressNode
FROM Hardware
GO

This will show you if the XPath is correctly targeting the right node before extracting its value.

内容的提问来源于stack exchange,提问作者103tech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:43:49